Issue
I am working on a GUI project with PySide (Qt) and planned to keep all backend/model code in python. This looked easy enough with normal Qt Widgets since it is easy to save a reference to the widget and then update properties as necessary. However I then saw QtQuick and have started to go that direction. The problem that I am having is that I can not seem to figure out how to access QML elements from Python. For example lets say I have a QML file with just a Text
element and I want to update that on some frequency. How would I gain access to the Text
element to be able to set the text
property? What is the standard way to accomplish this?
UPDATE - The marked answer is essentially what I am using with some additions. Not long before the answer was posted I found the reference page that explained all options (http://qt-project.org/doc/qt-4.8/qtbinding.html). The approach I am taking is to setup a class with a property that I want to be updated in the QML element, pass the object to setContextProperty(), reference the object.property in QML then be sure that a notify signal is setup so any change to the object will be reflected in QML. I'll post my code later so others can see it for future reference.
Solution
You can only access to most-top element properties. The "right" way should be using alias properties. If you want, for example, define a Label element (just a preconfigured Text element) you should do something like this:
// Label.qml
Item{
id: root
property alias text: txLabel.text
Text{
id: txLabel
anchors{ fill: parent; margins: 4 }
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
// ... other stuff
}
}
Every time you set to or get from Label.text, you are working with txLabel.text indeed.
I don't know how to expose variables from PySide to QML engine, but it should be like C++: setContextProperty() function or something else. So, in order to use our Label component. We can do:
// OurPage.qml
Item{
id: root
width: 800; height: 600
Text{
id: txCaption
anchors{ centerIn: parent }
text: qsTr("My name is:")
}
Label{
anchors{ top: textCaption }
text: myName
}
}
Where myName is a backend variable exported with setContextProperty("myName", pyVarMyName).
I hope this help you.
Answered By - Jairo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.