Qt for Python Signals and Slots: Difference between revisions
No edit summary |
No edit summary |
||
Line 7: | Line 7: | ||
This page describes the use of signals and slots in PySide. The emphasis is on illustrating the use of so-called new-style signals and slots, although the traditional syntax is also given as a reference. | This page describes the use of signals and slots in PySide. The emphasis is on illustrating the use of so-called new-style signals and slots, although the traditional syntax is also given as a reference. | ||
PyQt's new-style signals and slots were introduced in PyQt v4.5. The main goal of this new-style is to provide a more Pythonic syntax to Python programmers. PySide uses | PyQt's new-style signals and slots were introduced in PyQt v4.5. The main goal of this new-style is to provide a more Pythonic syntax to Python programmers. PySide uses "PSEP 100":http://www.pyside.org/docs/pseps/psep-0100.html as its implementation guideline. | ||
== Traditional syntax: SIGNAL () and SLOT() == | == Traditional syntax: SIGNAL () and SLOT() == | ||
Line 15: | Line 15: | ||
The example below uses the well known clicked signal from a ''QPushButton''. The connect method has a non python-friendly syntax. It is necessary to inform the object, its signal (via macro) and a slot to be connected to. | The example below uses the well known clicked signal from a ''QPushButton''. The connect method has a non python-friendly syntax. It is necessary to inform the object, its signal (via macro) and a slot to be connected to. | ||
<code> | <code> | ||
… | |||
def someFunc(): | def someFunc(): | ||
print "someFunc has been called!" | |||
… | … | ||
button = QtGui.QPushButton( | button = QtGui.QPushButton("Call someFunc") | ||
QtCore.QObject.connect(button, QtCore.SIGNAL (&#39;clicked()'), someFunc) | |||
… | … | ||
</code> | |||
== New syntax: Signal() and Slot() == | == New syntax: Signal() and Slot() == | ||
Line 29: | Line 33: | ||
The new-style uses a different syntax to create and to connect signals and slots. The previous example could be rewritten as: | The new-style uses a different syntax to create and to connect signals and slots. The previous example could be rewritten as: | ||
<code> | <code> | ||
… | |||
def someFunc(): | def someFunc(): | ||
print "someFunc has been called!" | |||
button = QtGui.QPushButton( | button = QtGui.QPushButton("Call someFunc") | ||
button.clicked.connect(someFunc) | |||
… | … | ||
</code> | |||
=== Using QtCore.Signal() === | === Using QtCore.Signal() === | ||
Line 59: | Line 67: | ||
* Hello World example: the basic example, showing how to connect a signal to a slot without any parameters. | * Hello World example: the basic example, showing how to connect a signal to a slot without any parameters. | ||
<code> | <code> | ||
#!/usr/bin/env python | |||
import sys | import sys | ||
from PySide import QtCore, QtGui | |||
# define a function that will be used as a slot | # define a function that will be used as a slot | ||
def sayHello(): | |||
print 'Hello world!' | |||
app = QtGui.QApplication(sys.argv) | app = QtGui.QApplication(sys.argv) | ||
Line 69: | Line 81: | ||
button = QtGui.QPushButton('Say hello!') | button = QtGui.QPushButton('Say hello!') | ||
# connect the clicked signal to the sayHello slot | # connect the clicked signal to the sayHello slot | ||
button.clicked.connect(sayHello) | |||
button.show() | |||
sys.exit(app.exec_()) | sys.exit(app.exec_()) | ||
</code> | |||
* Next, some arguments are added. This is a modified ''Hello World'' version. Some arguments are added to the slot and a new signal is created. | * Next, some arguments are added. This is a modified ''Hello World'' version. Some arguments are added to the slot and a new signal is created. | ||
<code> | <code> | ||
#!/usr/bin/env python | |||
import sys | import sys | ||
from PySide import QtCore | |||
# define a new slot that receives a string and has | # define a new slot that receives a string and has | ||
# 'saySomeWords' as its name | # 'saySomeWords' as its name | ||
&#64;QtCore.Slot(str) | |||
def saySomeWords(words): | |||
print words | |||
class Communicate(QtCore.QObject): | class Communicate(QtCore.QObject): | ||
# create a new signal on the fly and name it 'speak' | |||
speak = QtCore.Signal(str) | |||
someone = Communicate() | someone = Communicate() | ||
# connect signal and slot | |||
someone.speak.connect(saySomeWords) | |||
# emit 'speak' signal | |||
someone.speak.emit("Hello everybody!") | |||
</code> | |||
* Add some overloads. A small modification of the previous example, now with overloaded decorators. | * Add some overloads. A small modification of the previous example, now with overloaded decorators. | ||
<code> | <code> | ||
#!/usr/bin/env python | |||
import sys | import sys | ||
from PySide import QtCore | |||
# define a new slot that receives a C 'int' or a 'str' | # define a new slot that receives a C 'int' or a 'str' | ||
# and has 'saySomething' as its name | # and has 'saySomething' as its name | ||
&#64;QtCore.Slot(int) | |||
&#64;QtCore.Slot(str) | |||
def saySomething(stuff): | |||
print stuff | |||
class Communicate(QtCore.QObject): | class Communicate(QtCore.QObject): | ||
# create two new signals on the fly: one will handle | |||
# int type, the other will handle strings | |||
speakNumber = QtCore.Signal(int) | |||
speakWord = QtCore.Signal(str) | |||
someone = Communicate() | someone = Communicate() | ||
# connect signal and slot properly | |||
someone.speakNumber.connect(saySomething) | |||
someone.speakWord.connect(saySomething) | |||
# emit each 'speak' signal | |||
someone.speakNumber.emit(10) | |||
someone.speakWord.emit("Hello everybody!") | |||
</code> | |||
* An example with slot overloads and more complicated signal connections and emissions: | * An example with slot overloads and more complicated signal connections and emissions: | ||
<code> | <code> | ||
#!/usr/bin/env python | |||
import sys | import sys | ||
from PySide import QtCore | |||
# define a new slot that receives an C 'int' or a 'str' | # define a new slot that receives an C 'int' or a 'str' | ||
# and has 'saySomething' as its name | # and has 'saySomething' as its name | ||
&#64;QtCore.Slot(int) | |||
&#64;QtCore.Slot(str) | |||
def saySomething(stuff): | |||
print stuff | |||
class Communicate(QtCore.QObject): | class Communicate(QtCore.QObject): | ||
# create two new signals on the fly: one will handle | |||
# int type, the other will handle strings | |||
speak = QtCore.Signal((int,), (str,)) | |||
someone = Communicate() | someone = Communicate() | ||
# connect signal and slot. As 'int' is the default | |||
# we have to specify the str when connecting the | |||
# second signal | |||
someone.speak.connect(saySomething) | |||
someone.speak[str].connect(saySomething) | |||
# emit 'speak' signal with different arguments. | # emit 'speak' signal with different arguments. | ||
# we have to specify the str as int is the default | # we have to specify the str as int is the default | ||
someone.speak.emit(10) | |||
someone.speak[str].emit("Hello everybody!") | |||
</code> | |||
* An example of an object method emitting a signal: | * An example of an object method emitting a signal: | ||
<code> | <code> | ||
#!/usr/bin/env python | |||
import sys | import sys | ||
from PySide import QtCore | |||
class Communicate(QtCore.QObject): # [[Image:|Image:]]! Must inherit QObject for signals | class Communicate(QtCore.QObject): # [[Image:|Image:]]! Must inherit QObject for signals | ||
Line 125: | Line 188: | ||
speak = QtCore.Signal() | speak = QtCore.Signal() | ||
def ''init''(self): | def ''init''(self): | ||
# [[Image:|Image:]]! Must init QObject else runtime error: PySide.QtCore.Signal object has no attribute ‘emit’ | |||
super(Communicate, self).''init''() | |||
def speakingMethod(): | def speakingMethod(): | ||
self.speak.emit() | |||
someone = Communicate() | someone = Communicate() | ||
someone.speakingMethod() | |||
</code> | |||
* Signals are runtime objects owned by instances, they are not class attributes: | * Signals are runtime objects owned by instances, they are not class attributes: | ||
<code> | <code> | ||
Communicate.speak.connect(saySomething) # Erroneous: refers to class Communicate, not an instance of the class | |||
# raises exception: AttributeError: 'PySide.QtCore.Signal' object has no attribute 'connect' | # raises exception: AttributeError: 'PySide.QtCore.Signal' object has no attribute 'connect' | ||
</code> | |||
== PyQt Compatibility == | == PyQt Compatibility == | ||
Line 141: | Line 211: | ||
PyQt uses a different naming convention to its new signal/slot functions. In order to convert any PyQt script that uses this new-style to run with PySide, just use either of the proposed modifications below: | PyQt uses a different naming convention to its new signal/slot functions. In order to convert any PyQt script that uses this new-style to run with PySide, just use either of the proposed modifications below: | ||
<code> | <code> | ||
from PySide.QtCore import Signal as pyqtSignal | |||
from PySide.QtCore import Slot as pyqtSlot | |||
</code> | |||
or | or | ||
<code> | <code> | ||
QtCore.pyqtSignal = QtCore.Signal | |||
QtCore.pyqtSlot = QtCore.Slot | |||
</code> | |||
This way any call to ''pyqtSignal'' or ''pyqtSlot'' will be translated to a ''Signal'' or ''Slot'' call. | This way any call to ''pyqtSignal'' or ''pyqtSlot'' will be translated to a ''Signal'' or ''Slot'' call. |
Revision as of 08:36, 25 February 2015
Signals and Slots in PySide
This page describes the use of signals and slots in PySide. The emphasis is on illustrating the use of so-called new-style signals and slots, although the traditional syntax is also given as a reference.
PyQt's new-style signals and slots were introduced in PyQt v4.5. The main goal of this new-style is to provide a more Pythonic syntax to Python programmers. PySide uses "PSEP 100":http://www.pyside.org/docs/pseps/psep-0100.html as its implementation guideline.
Traditional syntax: SIGNAL () and SLOT()
QtCore.SIGNAL (...) and QtCore.SLOT (...) macros allow Python to interface with Qt signal and slot delivery mechanisms. This is the old way of using signals and slots.
The example below uses the well known clicked signal from a QPushButton. The connect method has a non python-friendly syntax. It is necessary to inform the object, its signal (via macro) and a slot to be connected to.
…
def someFunc():
print "someFunc has been called!"
…
button = QtGui.QPushButton("Call someFunc")
QtCore.QObject.connect(button, QtCore.SIGNAL (&#39;clicked()'), someFunc)
…
New syntax: Signal() and Slot()
The new-style uses a different syntax to create and to connect signals and slots. The previous example could be rewritten as:
…
def someFunc():
print "someFunc has been called!"
button = QtGui.QPushButton("Call someFunc")
button.clicked.connect(someFunc)
…
Using QtCore.Signal()
Signals can be defined using the QtCore.Signal() class. Python types and C types can be passed as parameters to it. If you need to overload it just pass the types as tuples or lists.
In addition to that, it can receive also a named argument name that defines the signal name. If nothing is passed as name then the new signal will have the same name as the variable that it is being assigned to.
The Examples section below has a collection of examples on the use of QtCore.Signal().
Note: Signals should be defined only within classes inheriting from QObject. This way the signal information is added to the class QMetaObject structure.
Using QtCore.Slot()
Slots are assigned and overloaded using the decorator QtCore.Slot(). Again, to define a signature just pass the types like the QtCore.Signal() class. Unlike the Signal() class, to overload a function, you don't pass every variation as tuple or list. Instead, you have to define a new decorator for every different signature. The examples section below will make it clearer.
Another difference is about its keywords. Slot() accepts a name and a result. The result keyword defines the type that will be returned and can be a C or Python type. name behaves the same way as in Signal(). If nothing is passed as name then the new slot will have the same name as the function that is being decorated.
Examples
The examples below illustrate how to define and connect signals and slots in PySide. Both basic connections and more complex examples are given.
- Hello World example: the basic example, showing how to connect a signal to a slot without any parameters.
#!/usr/bin/env python
import sys
from PySide import QtCore, QtGui
# define a function that will be used as a slot
def sayHello():
print 'Hello world!'
app = QtGui.QApplication(sys.argv)
button = QtGui.QPushButton('Say hello!')
# connect the clicked signal to the sayHello slot
button.clicked.connect(sayHello)
button.show()
sys.exit(app.exec_())
- Next, some arguments are added. This is a modified Hello World version. Some arguments are added to the slot and a new signal is created.
#!/usr/bin/env python
import sys
from PySide import QtCore
# define a new slot that receives a string and has
# 'saySomeWords' as its name
&#64;QtCore.Slot(str)
def saySomeWords(words):
print words
class Communicate(QtCore.QObject):
# create a new signal on the fly and name it 'speak'
speak = QtCore.Signal(str)
someone = Communicate()
# connect signal and slot
someone.speak.connect(saySomeWords)
# emit 'speak' signal
someone.speak.emit("Hello everybody!")
- Add some overloads. A small modification of the previous example, now with overloaded decorators.
#!/usr/bin/env python
import sys
from PySide import QtCore
# define a new slot that receives a C 'int' or a 'str'
# and has 'saySomething' as its name
&#64;QtCore.Slot(int)
&#64;QtCore.Slot(str)
def saySomething(stuff):
print stuff
class Communicate(QtCore.QObject):
# create two new signals on the fly: one will handle
# int type, the other will handle strings
speakNumber = QtCore.Signal(int)
speakWord = QtCore.Signal(str)
someone = Communicate()
# connect signal and slot properly
someone.speakNumber.connect(saySomething)
someone.speakWord.connect(saySomething)
# emit each 'speak' signal
someone.speakNumber.emit(10)
someone.speakWord.emit("Hello everybody!")
- An example with slot overloads and more complicated signal connections and emissions:
#!/usr/bin/env python
import sys
from PySide import QtCore
# define a new slot that receives an C 'int' or a 'str'
# and has 'saySomething' as its name
&#64;QtCore.Slot(int)
&#64;QtCore.Slot(str)
def saySomething(stuff):
print stuff
class Communicate(QtCore.QObject):
# create two new signals on the fly: one will handle
# int type, the other will handle strings
speak = QtCore.Signal((int,), (str,))
someone = Communicate()
# connect signal and slot. As 'int' is the default
# we have to specify the str when connecting the
# second signal
someone.speak.connect(saySomething)
someone.speak[str].connect(saySomething)
# emit 'speak' signal with different arguments.
# we have to specify the str as int is the default
someone.speak.emit(10)
someone.speak[str].emit("Hello everybody!")
- An example of an object method emitting a signal:
#!/usr/bin/env python
import sys
from PySide import QtCore
class Communicate(QtCore.QObject): # [[Image:|Image:]]! Must inherit QObject for signals
speak = QtCore.Signal()
def ''init''(self):
# [[Image:|Image:]]! Must init QObject else runtime error: PySide.QtCore.Signal object has no attribute ‘emit’
super(Communicate, self).''init''()
def speakingMethod():
self.speak.emit()
someone = Communicate()
someone.speakingMethod()
- Signals are runtime objects owned by instances, they are not class attributes:
Communicate.speak.connect(saySomething) # Erroneous: refers to class Communicate, not an instance of the class
# raises exception: AttributeError: 'PySide.QtCore.Signal' object has no attribute 'connect'
PyQt Compatibility
PyQt uses a different naming convention to its new signal/slot functions. In order to convert any PyQt script that uses this new-style to run with PySide, just use either of the proposed modifications below:
from PySide.QtCore import Signal as pyqtSignal
from PySide.QtCore import Slot as pyqtSlot
or
QtCore.pyqtSignal = QtCore.Signal
QtCore.pyqtSlot = QtCore.Slot
This way any call to pyqtSignal or pyqtSlot will be translated to a Signal or Slot call.
Other Notes
PyQt5 connect() always returns None, and raises an exception on failure to connect. The documents suggest that it returns a bool, but it always returns None. Instead of returning False, it raises an exception.