Qt wiki will be updated on October 12th 2023 starting at 11:30 AM (EEST) and the maintenance will last around 2-3 hours. During the maintenance the site will be unavailable.

Qt for Python/Connecting QML Signals: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
 
(10 intermediate revisions by 4 users not shown)
Line 1: Line 1:
[[Category:LanguageBindings::PySide]]
[[Category:Qt for Python]]
[[Category:Developing_with_Qt::Qt Quick]]
[[Category:Developing_with_Qt::Qt Quick]]
[toc align_right="yes" depth="3"]


= Connecting QML signals in PySide =
This page describes a few alternative approaches for connecting signals between QML and PySide. Simple illustrative examples about the signal connectivity are also provided in the [https://code.qt.io/cgit/pyside/pyside-setup.git/tree/examples/declarative/signals pyside-setup repository].
 
This page describes a few alternative approaches for connecting signals between QML and PySide. Simple illustrative examples about the signal connectivity are also provided in the "pyside-examples repository":http://qt.gitorious.org/pyside/pyside-examples/trees/master/examples/declarative/signals. Browse the git tree directly or "download a tarball of all examples":http://qt.gitorious.org/pyside/pyside-examples/archive-tarball/master and refer to the examples/declarative/signals directory.


== Connecting signals from QML to Python ==
== Connecting signals from QML to Python ==
Line 15: Line 12:
=== Explicitly calling a Python slot from QML ===
=== Explicitly calling a Python slot from QML ===


If the Python object is exposed to QML using <code>setContextProperty</code>, you can call any slot of the object explicitly from QML, as shown in "qmltopy1":http://qt.gitorious.org/pyside/pyside-examples/trees/master/examples/declarative/signals/qmltopy1. First, you define a class in Python, inheriting from QObject:
If the Python object is exposed to QML using <code>setContextProperty</code>, you can call any slot of the object explicitly from QML, as shown in [https://code.qt.io/cgit/pyside/pyside-setup.git/tree/examples/declarative/signals/qmltopy1 qmltopy1]. First, you define a class in Python, inheriting from QObject:


<code>
<syntaxhighlight lang="python" line="line">
class Console(QtCore.QObject):
class Console(QtCore.QObject):
&amp;#64;QtCore.Slot(str)
    @QtCore.Slot(str)
def outputStr(self, s):
    def outputStr(self, s):
print s
        print(s)
</code>
</syntaxhighlight>


Then, the Python object is instantiated and connected to the QML context:
Then, the Python object is instantiated and connected to the QML context:


<code>
<syntaxhighlight lang="python" line="line">
con = Console()
con = Console()
view = QtDeclarative.QDeclarativeView()
view = QtDeclarative.QDeclarativeView()
context = view.rootContext()
context = view.rootContext()
context.setContextProperty("con", con)
context.setContextProperty("con", con)
</code>
</syntaxhighlight>


After this, the object is accessible in QML and any slot can be called just like a function:
After this, the object is accessible in QML and any slot can be called just like a function:


<code>
<syntaxhighlight lang="javascript" line="line">
MouseArea {
MouseArea {
  onClicked: {
  onClicked: {
Line 41: Line 38:
  }
  }
}
}
</code>
</syntaxhighlight>


=== Returning a value from a slot ===
=== Returning a value from a slot ===


It is possible for slots to return values to the QML caller (see example "qmltopy2":http://qt.gitorious.org/pyside/pyside-examples/trees/master/examples/declarative/signals/qmltopy2). In this case, the Python slot needs to define an explicit return type:
It is possible for slots to return values to the QML caller (see example [https://code.qt.io/cgit/pyside/pyside-setup.git/tree/examples/declarative/signals/qmltopy2 qmltopy2]). In this case, the Python slot needs to define an explicit return type:


<code>
<syntaxhighlight lang="python" line="line">
&amp;#64;QtCore.Slot(result=int)
@QtCore.Slot(result=int)
def val(self):
def val(self):
self.r = self.r + 10
    self.r = self.r + 10
return self.r
    return self.r
</code>
</syntaxhighlight>


Then the Python object is exposed to QML, after which it can be called just like a function:
Then the Python object is exposed to QML, after which it can be called just like a function:


<code>
<syntaxhighlight lang="javascript" line="line">
onClicked: {
onClicked: {
helloText.rotation = rotatevalue.val()
    helloText.rotation = rotatevalue.val()
}
}
</code>
</syntaxhighlight>


=== Connecting signals from QML to Python using a top-level QML signal ===
=== Connecting signals from QML to Python using a top-level QML signal ===


If you prefer to handle the signal connection in Python, the simplest way to do it is to declare a top-level signal in QML and connect that to a Python slot as shown in "example qmltopy3":http://qt.gitorious.org/pyside/pyside-examples/trees/master/examples/declarative/signals/qmltopy3.
If you prefer to handle the signal connection in Python, the simplest way to do it is to declare a top-level signal in QML and connect that to a Python slot as shown in [https://code.qt.io/cgit/pyside/pyside-setup.git/tree/examples/declarative/signals/qmltopy3 example qmltopy3].


First, in the top-level QML item, declare the signal:
First, in the top-level QML item, declare the signal:


<code>
<syntaxhighlight lang="javascript" line="line">
Rectangle {
Rectangle {
id: page
    id: page


signal textRotationChanged(double rot)
    signal textRotationChanged(double rot)


[…]
    […]
</code>
</syntaxhighlight>


Then, in some other QML item, make some other signal handler emit this signal:
Then, in some other QML item, make some other signal handler emit this signal:


<code>
<syntaxhighlight lang="javascript" line="line">
onRotationChanged: textRotationChanged(rotation)
onRotationChanged: textRotationChanged(rotation)
</code>
</syntaxhighlight>


Finally, in Python, acquire the QML root object and connect the signal:
Finally, in Python, acquire the QML root object and connect the signal:


<code>
<syntaxhighlight lang="python" line="line">
root = view.rootObject()
root = view.rootObject()
root.textRotationChanged.connect(sayThis)
root.textRotationChanged.connect(sayThis)
</code>
</syntaxhighlight>


This approach has the benefit of hiding the Python class behaviour from QML. On the other hand, this approach requires the Python code to have some knowledge of the QML item contents.
This approach has the benefit of hiding the Python class behaviour from QML. On the other hand, this approach requires the Python code to have some knowledge of the QML item contents.
Line 94: Line 91:
=== Connecting a signal from a specific QML item to Python. ===
=== Connecting a signal from a specific QML item to Python. ===


It is also possible to acquire a specific QML item and connect a signal directly to it as illustrated in "example qmltopy4":http://qt.gitorious.org/pyside/pyside-examples/trees/master/examples/declarative/signals/qmltopy4.
It is also possible to acquire a specific QML item and connect a signal directly to it as illustrated in [https://code.qt.io/cgit/pyside/pyside-setup.git/tree/examples/declarative/signals/qmltopy4 example qmltopy4].


In principle, this approach doesn't require any extra consideration in QML. Unfortunately, in practice it may be difficult to find the proper QML items without assigning them object names:
In principle, this approach doesn't require any extra consideration in QML. Unfortunately, in practice it may be difficult to find the proper QML items without assigning them object names:


<code>
<syntaxhighlight lang="javascript" line="line">
MouseArea {
MouseArea {
id: buttonMouseArea
    id: buttonMouseArea
objectName: "buttonMouseArea"
    objectName: "buttonMouseArea"
anchors.fill: parent
    anchors.fill: parent
}
}
</code>
</syntaxhighlight>


Then, in Python, it is simple to find the desired item using <code>findChild</code> and connect a signal to it:
Then, in Python, it is simple to find the desired item using <code>findChild</code> and connect a signal to it:


<code>
<syntaxhighlight lang="python" line="line">
button = root.findChild(QtCore.QObject,"buttonMouseArea")
button = root.findChild(QtCore.QObject,"buttonMouseArea")
button.clicked.connect(lambda: sayThis("clicked button (signal directly connected)"))
button.clicked.connect(lambda: sayThis("clicked button (signal directly connected)"))
</code>
</syntaxhighlight>


Although initially tempting, this approach ties the QML and Python codebases pretty tightly to each other. Also, having to define the object names in QML makes the approach less than optimal.
Although initially tempting, this approach ties the QML and Python codebases pretty tightly to each other. Also, having to define the object names in QML makes the approach less than optimal.
Line 117: Line 114:
== Connecting signals from Python to QML ==
== Connecting signals from Python to QML ==


It is also possible to connect signals from Python to QML when e.g. changes in the model data need to be reflected in the UI. "Example pytoqml1":http://qt.gitorious.org/pyside/pyside-examples/trees/master/examples/declarative/signals/pytoqml1 illustrates how to do that.
It is also possible to connect signals from Python to QML when e.g. changes in the model data need to be reflected in the UI. [https://code.qt.io/cgit/pyside/pyside-setup.git/tree/examples/declarative/signals/pytoqml1 Example pytoqml1] illustrates how to do that.


First, a function is defined in QML:
First, a function is defined in QML:


<code>
<syntaxhighlight lang="javascript" line="line">
function updateRotater() {
function updateRotater() {
rotater.angle = rotater.angle + 45
    rotater.angle = rotater.angle + 45
}
}
</code>
</syntaxhighlight>


QML functions appear as slots in Python, so it's a simple matter to connect a signal to them:
QML functions appear as slots in Python, so it's a simple matter to connect a signal to them:


<code>
<syntaxhighlight lang="python" line="line">
timer.timeout.connect(root.updateRotater)
timer.timeout.connect(root.updateRotater)
</code>
</syntaxhighlight>


This allows for fairly clean and straightforward delivery of signals from Python to QML.
This allows for fairly clean and straightforward delivery of signals from Python to QML.

Latest revision as of 10:16, 9 February 2021


This page describes a few alternative approaches for connecting signals between QML and PySide. Simple illustrative examples about the signal connectivity are also provided in the pyside-setup repository.

Connecting signals from QML to Python

Connecting a signal from QML to Python is the most common use case. This allows for example connecting button clicks and other user interface events in QML to the backend logic written in Python.

There are multiple alternative methods for connecting QML signals to Python. The methods are not mutually exclusive; any of them can be used in a single program (and even for a single signal, if need be).

Explicitly calling a Python slot from QML

If the Python object is exposed to QML using

setContextProperty

, you can call any slot of the object explicitly from QML, as shown in qmltopy1. First, you define a class in Python, inheriting from QObject:

class Console(QtCore.QObject):
    @QtCore.Slot(str)
    def outputStr(self, s):
        print(s)

Then, the Python object is instantiated and connected to the QML context:

con = Console()
view = QtDeclarative.QDeclarativeView()
context = view.rootContext()
context.setContextProperty("con", con)

After this, the object is accessible in QML and any slot can be called just like a function:

MouseArea {
 onClicked: {
 con.outputStr("Hello, world!")
 }
}

Returning a value from a slot

It is possible for slots to return values to the QML caller (see example qmltopy2). In this case, the Python slot needs to define an explicit return type:

@QtCore.Slot(result=int)
def val(self):
    self.r = self.r + 10
    return self.r

Then the Python object is exposed to QML, after which it can be called just like a function:

onClicked: {
    helloText.rotation = rotatevalue.val()
}

Connecting signals from QML to Python using a top-level QML signal

If you prefer to handle the signal connection in Python, the simplest way to do it is to declare a top-level signal in QML and connect that to a Python slot as shown in example qmltopy3.

First, in the top-level QML item, declare the signal:

Rectangle {
    id: page

    signal textRotationChanged(double rot)

    []

Then, in some other QML item, make some other signal handler emit this signal:

onRotationChanged: textRotationChanged(rotation)

Finally, in Python, acquire the QML root object and connect the signal:

root = view.rootObject()
root.textRotationChanged.connect(sayThis)

This approach has the benefit of hiding the Python class behaviour from QML. On the other hand, this approach requires the Python code to have some knowledge of the QML item contents.

Connecting a signal from a specific QML item to Python.

It is also possible to acquire a specific QML item and connect a signal directly to it as illustrated in example qmltopy4.

In principle, this approach doesn't require any extra consideration in QML. Unfortunately, in practice it may be difficult to find the proper QML items without assigning them object names:

MouseArea {
    id: buttonMouseArea
    objectName: "buttonMouseArea"
    anchors.fill: parent
}

Then, in Python, it is simple to find the desired item using

findChild

and connect a signal to it:

button = root.findChild(QtCore.QObject,"buttonMouseArea")
button.clicked.connect(lambda: sayThis("clicked button (signal directly connected)"))

Although initially tempting, this approach ties the QML and Python codebases pretty tightly to each other. Also, having to define the object names in QML makes the approach less than optimal.

Connecting signals from Python to QML

It is also possible to connect signals from Python to QML when e.g. changes in the model data need to be reflected in the UI. Example pytoqml1 illustrates how to do that.

First, a function is defined in QML:

function updateRotater() {
    rotater.angle = rotater.angle + 45
}

QML functions appear as slots in Python, so it's a simple matter to connect a signal to them:

timer.timeout.connect(root.updateRotater)

This allows for fairly clean and straightforward delivery of signals from Python to QML.