Qt for Python Signals and Slots: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
(Fixed multiple issues in python sample)
m (make more clear that you should use [] with slots)
 
(6 intermediate revisions by 5 users not shown)
Line 1: Line 1:
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.


[[Category:PySide]]
The main goal of this new-style is to provide a more Pythonic syntax to Python programmers.
 
'''English''' [[Signals_and_Slots_in_PySide_Korean|한국어]] [[Signals_and_Slots_in_PySide_Japanese|日本語]]
 
 
 
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 [http://www.pyside.org/docs/pseps/psep-0100.html PSEP 100][pyside.org] as its implementation guideline.


== Traditional syntax: SIGNAL () and SLOT() ==
== 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.
''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.
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>
<syntaxhighlight lang="python" line="1">
import sys
from PySide2.QtWidgets import QApplication, QPushButton
from PySide2.QtCore import SIGNAL, QObject


def someFunc():
def func():
print "someFunc has been called!"
    print("func has been called!")


app = QApplication(sys.argv)
button = QPushButton("Call func")
QObject.connect(button, SIGNAL ('clicked()'), func)
button.show()                                                                                           


button = QtGui.QPushButton("Call someFunc")
sys.exit(app.exec_())
QtCore.QObject.connect(button, QtCore.SIGNAL ('clicked()'), someFunc)
</syntaxhighlight>
 
</code>


== New syntax: Signal() and Slot() ==
== 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:
The new-style uses a different syntax to create and to connect signals and slots.
The previous example could be rewritten as:


<code>
<syntaxhighlight lang="python" line="1">
import sys
from PySide2.QtWidgets import QApplication, QPushButton


def someFunc():
def func():
  print "someFunc has been called!"
  print("func has been called!")


button = QtGui.QPushButton("Call someFunc")
app = QApplication(sys.argv)
button.clicked.connect(someFunc)
button = QPushButton("Call func")
 
button.clicked.connect(func)
button.show()
</code>
sys.exit(app.exec_())
</syntaxhighlight>


=== Using QtCore.Signal() ===
=== 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.
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.
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()''.
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.
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() ===
=== 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.
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.
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 ===
=== Examples ===


The examples below illustrate how to define and connect signals and slots in PySide. Both basic connections and more complex examples are given.
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.
* Hello World example: the basic example, showing how to connect a signal to a slot without any parameters.


<code>
<syntaxhighlight lang="python" line="line">
#!/usr/bin/env python
 
import sys
import sys
from PySide import QtCore, QtGui
from PySide2 import QtCore, QtGui


# define a function that will be used as a slot
# define a function that will be used as a slot
Line 87: Line 100:


sys.exit(app.exec_())
sys.exit(app.exec_())
</code>
</syntaxhighlight>


* 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>
<syntaxhighlight lang="python" line="line">
#!/usr/bin/env python
import sys                                                                 
from PySide2.QtWidgets import QApplication, QPushButton                   
from PySide2.QtCore import QObject, Signal, Slot                           
                                                                           
app = QApplication(sys.argv)                                               
                                                                           
# define a new slot that receives a string and has                         
# 'saySomeWords' as its name                                               
@Slot(str)                                                                 
def say_some_words(words):                                                 
    print(words)                                                             
                                                                           
class Communicate(QObject):                                               
# create a new signal on the fly and name it 'speak'                     
speak = Signal(str)                                                       
                                                                           
someone = Communicate()                                                   
# connect signal and slot                                                 
someone.speak.connect(say_some_words)                                       
# emit 'speak' signal                                                       
someone.speak.emit("Hello everybody!")
</syntaxhighlight>


import sys
* Add some overloads. A small modification of the previous example, now with overloaded decorators.
from PySide import QtCore


# define a new slot that receives a string and has
<syntaxhighlight lang="python" line="line">
# 'saySomeWords' as its name
import sys                                                                 
@QtCore.Slot(str)
from PySide2.QtWidgets import QApplication, QPushButton                   
def saySomeWords(words):
from PySide2.QtCore import QObject, Signal, Slot                           
print words
                                                                           
app = QApplication(sys.argv)                                               
                                                                           
# define a new slot that receives a C 'int' or a 'str'                     
# and has 'saySomething' as its name                                      
@Slot(int)                                                                 
@Slot(str)                                                                
def say_something(stuff):                                                  
    print(stuff)                                                           
                                                                           
class Communicate(QObject):                                               
    # create two new signals on the fly: one will handle                   
    # int type, the other will handle strings                             
    speak_number = Signal(int)                                             
    speak_word = Signal(str)                                                 
                                                                           
someone = Communicate()                                                   
# connect signal and slot properly                                         
someone.speak_number.connect(say_something)                               
someone.speak_word.connect(say_something)                                 
# emit each 'speak' signal                                                 
someone.speak_number.emit(10)                                             
someone.speak_word.emit("Hello everybody!")
</syntaxhighlight>


class Communicate(QtCore.QObject):
* An example with slot overloads and more complicated signal connections and emissions (note that when passing arguments to a signal you use "[]"):
# create a new signal on the fly and name it 'speak'
speak = QtCore.Signal(str)


someone = Communicate()
<syntaxhighlight lang="python" line="line">
# connect signal and slot
import sys
someone.speak.connect(saySomeWords)
from PySide2.QtWidgets import QApplication, QPushButton
# emit 'speak' signal
from PySide2.QtCore import QObject, Signal, Slot
someone.speak.emit("Hello everybody!")
</code>


* Add some overloads. A small modification of the previous example, now with overloaded decorators.
app = QApplication(sys.argv)
 
<code>
#!/usr/bin/env python
 
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
@QtCore.Slot(int)
@Slot(int)
@QtCore.Slot(str)
@Slot(str)
def saySomething(stuff):
def say_something(stuff):
print 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!")
</code>
 
* An example with slot overloads and more complicated signal connections and emissions:
 
<code>
#!/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
@QtCore.Slot(int)
@QtCore.Slot(str)
def saySomething(stuff):
print stuff


class Communicate(QtCore.QObject):
class Communicate(QObject):
# create two new signals on the fly: one will handle
    # create two new signals on the fly: one will handle
# int type, the other will handle strings
    # int type, the other will handle strings
speak = QtCore.Signal((int,), (str,))
    speak = Signal((int,), (str,))


someone = Communicate()
someone = Communicate()
Line 168: Line 184:
# we have to specify the str when connecting the
# we have to specify the str when connecting the
# second signal
# second signal
someone.speak.connect(saySomething)
someone.speak.connect(say_something)
someone.speak[str].connect(saySomething)
someone.speak[str].connect(say_something)


# emit 'speak' signal with different arguments.
# emit 'speak' signal with different arguments.
Line 175: Line 191:
someone.speak.emit(10)
someone.speak.emit(10)
someone.speak[str].emit("Hello everybody!")
someone.speak[str].emit("Hello everybody!")
</code>
</syntaxhighlight>


* An example of an object method emitting a signal:
* An example of an object method emitting a signal:


<code>
<syntaxhighlight lang="python" line="line">
#!/usr/bin/env python
import sys                                                                 
from PySide2.QtCore import QObject, Signal                                 
                                                                           
# Must inherit QObject for signals                                         
class Communicate(QObject):                                               
    speak = Signal()                                                       
             
    def __init__(self):                                                   
        super(Communicate, self).__init__()   
        self.speak.connect(self.say_hello)                           
                                                                           
    def speaking_method(self):                                             
        self.speak.emit() 


import sys
    def say_hello(self):
from PySide import QtCore
        print("Hello")                                               


class Communicate(QtCore.QObject): # Must inherit QObject for signals
                                                                           
    speak = QtCore.Signal()
someone = Communicate()                                                
someone.speaking_method()  
</syntaxhighlight>


    def __init__(self): # Must init QObject else runtime error: PySide.QtCore.Signal object has no attribute ‘emit’
* An example of a signal emitted from another QThread:
        super(Communicate, self).__init__()


    def speakingMethod(self):
<syntaxhighlight lang="python" line="line">
        self.speak.emit()
import sys                                                                 
from PySide2.QtCore import QObject, Slot, Signal, QThread                                 


someone = Communicate()
# Create the Slots that will receive signals
someone.speakingMethod()
@Slot(str)
</code>
def update_a_str_field(message):
    print(message)


* Signals are runtime objects owned by instances, they are not class attributes:
@Slot(int)
def update_a_int_field(self, value):
    print(value)


<code>
# Signals must inherit QObject                             
Communicate.speak.connect(saySomething) # Erroneous: refers to class Communicate, not an instance of the class
class Communicate(QObject):                                                
    signal_str = Signal(str)
    signal_int = Signal(int)


# raises exception: AttributeError: 'PySide.QtCore.Signal' object has no attribute 'connect'
class WorkerThread(QThread):
</code>
    def __init__(self, parent=None):
        QThread.__init__(self, parent)
        self.signals = Communicate()
        # Connect the signals to the main thread slots
        self.signals.signal_str.connect(parent.update_a_str_field)
        self.signals.signal_int.connect(parent.update_a_int_field)


== PyQt Compatibility ==
    def run(self):
        self.signals.update_a_int_field.emit(1)
        self.signals.update_a_str_field.emit("Hello World.")
</syntaxhighlight>


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:
* Signals are runtime objects owned by instances, they are not class attributes:
 
<code>
from PySide.QtCore import Signal as pyqtSignal
from PySide.QtCore import Slot as pyqtSlot
</code>
 
or
 
<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.
 
== 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.
<syntaxhighlight lang="python" line="line">
# Erroneous: refers to class Communicate, not an instance of the class
Communicate.speak.connect(say_something)
# raises exception: AttributeError: 'PySide2.QtCore.Signal' object has no attribute 'connect'
</syntaxhighlight>

Latest revision as of 14:40, 5 September 2019

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.

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.

import sys
from PySide2.QtWidgets import QApplication, QPushButton
from PySide2.QtCore import SIGNAL, QObject

def func():
    print("func has been called!")

app = QApplication(sys.argv)
button = QPushButton("Call func")
QObject.connect(button, SIGNAL ('clicked()'), func)
button.show()                                                                                             

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:

import sys
from PySide2.QtWidgets import QApplication, QPushButton

def func():
 print("func has been called!")

app = QApplication(sys.argv)
button = QPushButton("Call func")
button.clicked.connect(func)
button.show()
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.
import sys
from PySide2 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.
import sys                                                                  
from PySide2.QtWidgets import QApplication, QPushButton                     
from PySide2.QtCore import QObject, Signal, Slot                            
                                                                            
app = QApplication(sys.argv)                                                
                                                                            
# define a new slot that receives a string and has                          
# 'saySomeWords' as its name                                                
@Slot(str)                                                                  
def say_some_words(words):                                                  
    print(words)                                                               
                                                                            
class Communicate(QObject):                                                 
 # create a new signal on the fly and name it 'speak'                       
 speak = Signal(str)                                                        
                                                                            
someone = Communicate()                                                     
# connect signal and slot                                                   
someone.speak.connect(say_some_words)                                         
# emit 'speak' signal                                                         
someone.speak.emit("Hello everybody!")
  • Add some overloads. A small modification of the previous example, now with overloaded decorators.
import sys                                                                  
from PySide2.QtWidgets import QApplication, QPushButton                     
from PySide2.QtCore import QObject, Signal, Slot                            
                                                                            
app = QApplication(sys.argv)                                                
                                                                            
# define a new slot that receives a C 'int' or a 'str'                      
# and has 'saySomething' as its name                                        
@Slot(int)                                                                  
@Slot(str)                                                                  
def say_something(stuff):                                                   
    print(stuff)                                                            
                                                                            
class Communicate(QObject):                                                 
    # create two new signals on the fly: one will handle                    
    # int type, the other will handle strings                               
    speak_number = Signal(int)                                              
    speak_word = Signal(str)                                                  
                                                                            
someone = Communicate()                                                     
# connect signal and slot properly                                          
someone.speak_number.connect(say_something)                                 
someone.speak_word.connect(say_something)                                   
# emit each 'speak' signal                                                  
someone.speak_number.emit(10)                                               
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 "[]"):
import sys
from PySide2.QtWidgets import QApplication, QPushButton
from PySide2.QtCore import QObject, Signal, Slot

app = QApplication(sys.argv)

# define a new slot that receives a C 'int' or a 'str'
# and has 'saySomething' as its name
@Slot(int)
@Slot(str)
def say_something(stuff):
    print(stuff)

class Communicate(QObject):
    # create two new signals on the fly: one will handle
    # int type, the other will handle strings
    speak = 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(say_something)
someone.speak[str].connect(say_something)

# 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:
import sys                                                                  
from PySide2.QtCore import QObject, Signal                                  
                                                                            
# Must inherit QObject for signals                                          
class Communicate(QObject):                                                 
    speak = Signal()                                                        
              
    def __init__(self):                                                     
        super(Communicate, self).__init__()    
        self.speak.connect(self.say_hello)                             
                                                                            
    def speaking_method(self):                                              
        self.speak.emit()   

    def say_hello(self):
        print("Hello")                                                

                                                                            
someone = Communicate()                                                 
someone.speaking_method()
  • An example of a signal emitted from another QThread:
import sys                                                                  
from PySide2.QtCore import QObject, Slot, Signal, QThread                                  

# Create the Slots that will receive signals
@Slot(str)
def update_a_str_field(message):
    print(message)

@Slot(int)
def update_a_int_field(self, value):
    print(value)

# Signals must inherit QObject                              
class Communicate(QObject):                                                 
    signal_str = Signal(str)
    signal_int = Signal(int)

class WorkerThread(QThread):
    def __init__(self, parent=None):
        QThread.__init__(self, parent)
        self.signals = Communicate()
        # Connect the signals to the main thread slots
        self.signals.signal_str.connect(parent.update_a_str_field)
        self.signals.signal_int.connect(parent.update_a_int_field)

    def run(self):
        self.signals.update_a_int_field.emit(1)
        self.signals.update_a_str_field.emit("Hello World.")
  • Signals are runtime objects owned by instances, they are not class attributes:
# Erroneous: refers to class Communicate, not an instance of the class
Communicate.speak.connect(say_something)
# raises exception: AttributeError: 'PySide2.QtCore.Signal' object has no attribute 'connect'