Qt for Python Signals and Slots
This page describes the use of signals and slots in Qt for Python. 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.
The main goal of this new-style is to provide a more Pythonic syntax to Python programmers.
Contents
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.
1 import sys 2 from PySide2.QtWidgets import QApplication, QPushButton 3 from PySide2.QtCore import SIGNAL, QObject 4 5 def func(): 6 print("func has been called!") 7 8 app = QApplication(sys.argv) 9 button = QPushButton("Call func") 10 QObject.connect(button, SIGNAL ('clicked()'), func) 11 button.show() 12 13 sys.exit(app.exec_())
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:
1 import sys 2 from PySide2.QtWidgets import QApplication, QPushButton 3 4 def func(): 5 print("func has been called!") 6 7 app = QApplication(sys.argv) 8 button = QPushButton("Call func") 9 button.clicked.connect(func) 10 button.show() 11 sys.exit(app.exec_())
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 PySide2. 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.
1 import sys 2 from PySide2 import QtCore, QtGui 3 4 # define a function that will be used as a slot 5 def sayHello(): 6 print 'Hello world!' 7 8 app = QtGui.QApplication(sys.argv) 9 10 button = QtGui.QPushButton('Say hello!') 11 12 # connect the clicked signal to the sayHello slot 13 button.clicked.connect(sayHello) 14 button.show() 15 16 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.
1 import sys 2 from PySide2.QtWidgets import QApplication, QPushButton 3 from PySide2.QtCore import QObject, Signal, Slot 4 5 app = QApplication(sys.argv) 6 7 # define a new slot that receives a string and has 8 # 'saySomeWords' as its name 9 @Slot(str) 10 def say_some_words(words): 11 print(words) 12 13 class Communicate(QObject): 14 # create a new signal on the fly and name it 'speak' 15 speak = Signal(str) 16 17 someone = Communicate() 18 # connect signal and slot 19 someone.speak.connect(say_some_words) 20 # emit 'speak' signal 21 someone.speak.emit("Hello everybody!")
- Add some overloads. A small modification of the previous example, now with overloaded decorators.
1 import sys 2 from PySide2.QtWidgets import QApplication, QPushButton 3 from PySide2.QtCore import QObject, Signal, Slot 4 5 app = QApplication(sys.argv) 6 7 # define a new slot that receives a C 'int' or a 'str' 8 # and has 'saySomething' as its name 9 @Slot(int) 10 @Slot(str) 11 def say_something(stuff): 12 print(stuff) 13 14 class Communicate(QObject): 15 # create two new signals on the fly: one will handle 16 # int type, the other will handle strings 17 speak_number = Signal(int) 18 speak_word = Signal(str) 19 20 someone = Communicate() 21 # connect signal and slot properly 22 someone.speak_number.connect(say_something) 23 someone.speak_word.connect(say_something) 24 # emit each 'speak' signal 25 someone.speak_number.emit(10) 26 someone.speak_word.emit("Hello everybody!")
- An example with slot overloads and more complicated signal connections and emissions (note that when passing arguments to a signal you use «[]»):
1 import sys 2 from PySide2.QtWidgets import QApplication, QPushButton 3 from PySide2.QtCore import QObject, Signal, Slot 4 5 app = QApplication(sys.argv) 6 7 # define a new slot that receives a C 'int' or a 'str' 8 # and has 'saySomething' as its name 9 @Slot(int) 10 @Slot(str) 11 def say_something(stuff): 12 print(stuff) 13 14 class Communicate(QObject): 15 # create two new signals on the fly: one will handle 16 # int type, the other will handle strings 17 speak = Signal((int,), (str,)) 18 19 someone = Communicate() 20 # connect signal and slot. As 'int' is the default 21 # we have to specify the str when connecting the 22 # second signal 23 someone.speak.connect(say_something) 24 someone.speak[str].connect(say_something) 25 26 # emit 'speak' signal with different arguments. 27 # we have to specify the str as int is the default 28 someone.speak.emit(10) 29 someone.speak[str].emit("Hello everybody!")
1 import sys 2 from PySide2.QtCore import QObject, Signal 3 4 # Must inherit QObject for signals 5 class Communicate(QObject): 6 speak = Signal() 7 8 def __init__(self): 9 super(Communicate, self).__init__() 10 self.speak.connect(self.say_hello) 11 12 def speaking_method(self): 13 self.speak.emit() 14 15 def say_hello(self): 16 print("Hello") 17 18 19 someone = Communicate() 20 someone.speaking_method()
1 import sys 2 from PySide2.QtCore import QObject, Slot, Signal, QThread 3 4 # Create the Slots that will receive signals 5 @Slot(str) 6 def update_a_str_field(message): 7 print(message) 8 9 @Slot(int) 10 def update_a_int_field(self, value): 11 print(value) 12 13 # Signals must inherit QObject 14 class Communicate(QObject): 15 signal_str = Signal(str) 16 signal_int = Signal(int) 17 18 class WorkerThread(QThread): 19 def __init__(self, parent=None): 20 QThread.__init__(self, parent) 21 self.signals = Communicate() 22 # Connect the signals to the main thread slots 23 self.signals.signal_str.connect(parent.update_a_str_field) 24 self.signals.signal_int.connect(parent.update_a_int_field) 25 26 def run(self): 27 self.signals.update_a_int_field.emit(1) 28 self.signals.update_a_str_field.emit("Hello World.")
1 # Erroneous: refers to class Communicate, not an instance of the class 2 Communicate.speak.connect(say_something) 3 # raises exception: AttributeError: 'PySide2.QtCore.Signal' object has no attribute 'connect'