Qt Signal Slot Same Class

broken image


Check it out on Github Last updated: 23/08/2020 10:33:32

QGIS Tutorials

This tutorial is part of our QGIS tutorial series:

This is a brief explanation of the concept of signal and slot in PyQt5, which is the GUI framework for QGIS plugins.

In summary, this very much resembles events and callbacks in JavaScript. It's an asynchronous mechanism to let one part of a program know when another part of a program was updated, which is a most crucial concept in GUI programming. You master signal/slot, you master a whole lot about plugin development in QGIS.

Qt Signal Slot Thread

General concept

Class

Generally a signal is a trigger which can be emitted (hence the term signal) and carry an arbitrary amount of information when it is emitted.

Signals and slots were one of the distinguishing features that made Qt an exciting and innovative tool back in time. But sometimes you can teach new tricks to an old dog, and QObjects gained a new way to connect between signals and slots in Qt5, plus some extra features to connect to other functions which are not slots. @SGaist said in Signals and Slots within same Class: There's no event loop running at that point of your code hence the slot is not called. @SGaist said in Signals and Slots within same Class: There's no event loop running at that point of your code hence the slot is not called.

The signal can be connected to a slot, which needs to be Python callable (in other words, a method or a class, anything implementing the __call__ magic), which can be any arbitrary function. The slot can accept the information which is emitted by the signal to process it further.

This is useful when one object needs to know about the actions of another object. For instance, if your plugin features a button that should paste the clipboard contents into a text field, then your plugin would need to know which function to call once the button is clicked. This is typically done via signal and slot.

Signal

A signalhas to be a class attribute of a descendant of QObject. Any QGIS widget and almost all GUI classes are descendants of QObject (i.e. have QObject as the very basic parent class) and they all come with predefined signals, such as QgsFilterLineEdit's valueChanged signal, which is triggered when a user changes the text of the widget.

Definition

A signal has the general definition of PyQt5.QtCore.pyqtSignal(types), where types will be the data type(s) a signal can emit:

  • any basic Python data type (int, str, list etc.) or C++ type. In the latter case it needs to be defined as a string, e.g. pyqtSignal(int) or pyqtSignal('QgsPointXY')
  • multiple Python or C++ types, which will emit several values, e.g. pyqtSignal(int, str) will take two arguments
  • multiple sequences, which will create multiple versions of the signal, i.e. signal overloads, e.g. pyqtSignal([int], ['QgsPointXY'])

The first two options are fairly easy to grasp. However, the latter is a little more mysterious. Basically, overloaded signatures are a way to define the same object or class in multiple ways (you might call it Schrödinger's signal). The concept of overloaded class definitions is not really a thing in Python, though it can be done. If you define a signal with overloaded signatures, it's like you're creating the same object multiple times with different arguments, e.g. the example above would translate to:

This method to define a signal is a little more elaborate as we'll see soon, but very handy.

Methods

connect()

This method connects the signal to a slot. I.e. the signal can connect to a function, which takes its arguments and does something with them. For all practical purposes, you'll only need to pass the slot function to connect(). Each signal can connect to an arbitrary amount of slot functions.

disconnect()

Often you want to disconnect a slot from its signal to control whether the slot function should still be executed when the signal is triggered. You can either pass the specific slot function or nothing, in which case all slots for the signal will be disconnected.

Slots

Generally a signal is a trigger which can be emitted (hence the term signal) and carry an arbitrary amount of information when it is emitted.

Signals and slots were one of the distinguishing features that made Qt an exciting and innovative tool back in time. But sometimes you can teach new tricks to an old dog, and QObjects gained a new way to connect between signals and slots in Qt5, plus some extra features to connect to other functions which are not slots. @SGaist said in Signals and Slots within same Class: There's no event loop running at that point of your code hence the slot is not called. @SGaist said in Signals and Slots within same Class: There's no event loop running at that point of your code hence the slot is not called.

The signal can be connected to a slot, which needs to be Python callable (in other words, a method or a class, anything implementing the __call__ magic), which can be any arbitrary function. The slot can accept the information which is emitted by the signal to process it further.

This is useful when one object needs to know about the actions of another object. For instance, if your plugin features a button that should paste the clipboard contents into a text field, then your plugin would need to know which function to call once the button is clicked. This is typically done via signal and slot.

Signal

A signalhas to be a class attribute of a descendant of QObject. Any QGIS widget and almost all GUI classes are descendants of QObject (i.e. have QObject as the very basic parent class) and they all come with predefined signals, such as QgsFilterLineEdit's valueChanged signal, which is triggered when a user changes the text of the widget.

Definition

A signal has the general definition of PyQt5.QtCore.pyqtSignal(types), where types will be the data type(s) a signal can emit:

  • any basic Python data type (int, str, list etc.) or C++ type. In the latter case it needs to be defined as a string, e.g. pyqtSignal(int) or pyqtSignal('QgsPointXY')
  • multiple Python or C++ types, which will emit several values, e.g. pyqtSignal(int, str) will take two arguments
  • multiple sequences, which will create multiple versions of the signal, i.e. signal overloads, e.g. pyqtSignal([int], ['QgsPointXY'])

The first two options are fairly easy to grasp. However, the latter is a little more mysterious. Basically, overloaded signatures are a way to define the same object or class in multiple ways (you might call it Schrödinger's signal). The concept of overloaded class definitions is not really a thing in Python, though it can be done. If you define a signal with overloaded signatures, it's like you're creating the same object multiple times with different arguments, e.g. the example above would translate to:

This method to define a signal is a little more elaborate as we'll see soon, but very handy.

Methods

connect()

This method connects the signal to a slot. I.e. the signal can connect to a function, which takes its arguments and does something with them. For all practical purposes, you'll only need to pass the slot function to connect(). Each signal can connect to an arbitrary amount of slot functions.

disconnect()

Often you want to disconnect a slot from its signal to control whether the slot function should still be executed when the signal is triggered. You can either pass the specific slot function or nothing, in which case all slots for the signal will be disconnected.

emit()

When called, it emits values of the data types you specified when defining the signal (if any). These values have to be in the same order as in the definition, i.e. if pyqtSignal(int, str) was the definition, the signal needs to e.g. emit(4, 'blabla'), not emit('blabla', 4).

Examples

Let's see how this would work with more practical examples. To more relate to QGIS plugins, I'll use a similar (harshly abstracted) barebone structure as in our Interactive QGIS Plugin tutorial to depict the general usage when e.g. defining a new Map Tool (QgsMapTool).

Simple Example

This is only non-working pseudo-code, which will just demonstrate the general usage. A map tool is created which implements a canvasReleaseEvent event emitting a custom signal when triggered. This signal connects to a custom slot function in the main plugin code.

So, this hypothetical plugin would capture the point clicked by a user upon releasing the mouse button and print the WKT (Well Known Text) representation of that point to the Python console. Not very useful, I know, but I hope it gets the point across.

Overloaded signal example

Let's get a little fancier and say we want to print the distance of that point to our location when we click the mouse, but the WKT representation when we release the mouse button.

We can achieve this with the exact same signal if we define it with an overloaded signature. Yep, finally seeing how a Schrödinger's signal can work:

We now defined another canvasPressEvent, which will be triggered if the user presses the map canvas while the NewMapTool is active.

Qt Signal Slot Parameter

Since we defined our canvasClicked event now with the overloaded signature pyqtSignal([int], ['QgsPointXY']), we need to watch out that we only call the right signature for connect() and emit(). If we would omit the specific signature when calling these functions, they would use the first signature they find, which would be int in this case.

We connected both signatures to separate functions. Now, when the user clicks in the map canvas, the distance of the point to 13.413513, 52.491019 will be printed (*), when he releases the mouse button, the point's WKT representation will be printed.

Be aware however, that overloaded signatures have a catch: the Python data types in the pyqtSignal definition are converted to C++ types and some combinations can lead to undesired outcomes. E.g. pyqtSignal(, [dict]) will be converted to the same C++ data type. Calling emit() or connect() on the dict signature will be interpreted as calling the method on the list signature instead.

(*) Note, that those coordinates are in X, Y WGS84. The point captured by the canvasPressEvent depends on the map canvas CRS which is likely different, so you'd need to transform. Even if it were WGS84, the distance would be in degrees.

One key and distinctive feature of Qt framework is the use of signals and slots to connect widgets and related actions. But as powerful the feature is, it may look compelling to a lot of developers not used to such a model, and it may take some time at the beginning to get used to understand how to use signals and slots properly. However, since version 4.4, we can relay on

Qt Signal Slot Same Classification

auto-connections to simplify using this feature.
Back in the old days, signals and slots connections were set up for compile time (or even run time) manually, where developers used the following sentence:

Qt Signal Slot Performance


this is, we stated the sender object's name, the signal we want to connect, the receiver object's name and the slot to connect the signal to.
Now there's an automatic way to connect signals and slots by means of QMetaObject's ability to make connections between signals and suitably-named slots. And that's the key: if we use an appropriate naming convention, signals and slots will be properly connected without the need to write additional code for that to happen. So by declaring and implementing a slot with a name that follows the following convention:
uic (the User Interface Compiler of Qt) will automatically generate code in the dialog's setupUi() function to connect button's signal with dialog's slot.
So back to our example, the class implementing the slot must define it like this:
We then write the method's implementatio to carry on an action when the signal is emitted:
In brief, we have seen that by using automatic connection of signals and slots we can count on both a standard naming convention and at the same time an explicit interface for designers to embrace. If the proper source code implements such a given interface, interface designers can later check that everything is working fine without the need to code.



broken image