Signals And Slots Pyqt5

3/24/2022by admin

Signals are connected to slots which are functions (or methods) which will be run every time the signal fires. Many signals also transmit data, providing information about the state change or widget that fired them. The receiving slot can use this data to perform different actions in response to the same signal. PyQt5 allows you to use Qt classes that can process QML code, and therefore you can write an interface to QML, and also send signals to the QML layer and invoke slots of objects inherited from QObject from the QML layer. To get meet with such possibilities of PyQt5, we will write a program that implements the following tasks.

Build complex application behaviours using signals and slots, and override widget event handling with custom events.

As already described, every interaction the user has with a Qt application causes an Event. There are multiple types of event, each representing a difference type of interaction — e.g. mouse or keyboard events.

Events that occur are passed to the event-specific handler on the widget where the interaction occurred. For example, clicking on a widget will cause a QMouseEvent to be sent to the .mousePressEvent event handler on the widget. This handler can interrogate the event to find out information, such as what triggered the event and where specifically it occurred.

You can intercept events by subclassing and overriding the handler function on the class, as you would for any other function. You can choose to filter, modify, or ignore events, passing them through to the normal handler for the event by calling the parent class function with super().

However, imagine you want to catch an event on 20 different buttons. Subclassing like this now becomes an incredibly tedious way of catching, interpreting and handling these events.

python

Thankfully Qt offers a neater approach to receiving notification of things happening in your application: Signals.

Signals

Instead of intercepting raw events, signals allow you to 'listen' for notifications of specific occurrences within your application. While these can be similar to events — a click on a button — they can also be more nuanced — updated text in a box. Data can also be sent alongside a signal - so as well as being notified of the updated text you can also receive it.

The receivers of signals are called Slots in Qt terminology. A number of standard slots are provided on Qt classes to allow you to wire together different parts of your application. However, you can also use any Python function as a slot, and therefore receive the message yourself.

Load up a fresh copy of `MyApp_window.py` and save it under a new name for this section. The code is copied below if you don't have it yet.

Basic signals

First, let's look at the signals available for our QMainWindow. You can find this information in the Qt documentation. Scroll down to the Signals section to see the signals implemented for this class.

Qt 5 Documentation — QMainWindow Signals

As you can see, alongside the two QMainWindow signals, there are 4 signals inherited from QWidget and 2 signals inherited from Object. If you click through to the QWidget signal documentation you can see a .windowTitleChanged signal implemented here. Next we'll demonstrate that signal within our application.

Pyqt5 new style signals and slots

Qt 5 Documentation — Widget Signals

The code below gives a few examples of using the windowTitleChanged signal.

python

Try commenting out the different signals and seeing the effect on what the slot prints.

We start by creating a function that will behave as a ‘slot’ for our signals.

Then we use .connect on the .windowTitleChanged signal. We pass the function that we want to be called with the signal data. In this case the signal sends a string, containing the new window title.

If we run that, we see that we receive the notification that the window title has changed.

Events

Next, let’s take a quick look at events. Thanks to signals, for most purposes you can happily avoid using events in Qt, but it’s important to understand how they work for when they are necessary.

As an example, we're going to intercept the .contextMenuEvent on QMainWindow. This event is fired whenever a context menu is about to be shown, and is passed a single value event of type QContextMenuEvent.

To intercept the event, we simply override the object method with our new method of the same name. So in this case we can create a method on our MainWindow subclass with the name contextMenuEvent and it will receive all events of this type.

If you add the above method to your MainWindow class and run your program you will discover that right-clicking in your window now displays the message in the print statement.

Sometimes you may wish to intercept an event, yet still trigger the default (parent) event handler. You can do this by calling the event handler on the parent class using super as normal for Python class methods.

python
Signals and slots example pyqt5

This allows you to propagate events up the object hierarchy, handling only those parts of an event handler that you wish.

However, in Qt there is another type of event hierarchy, constructed around the UI relationships. Widgets that are added to a layout, within another widget, may opt to pass their events to their UI parent. In complex widgets with multiple sub-elements this can allow for delegation of event handling to the containing widget for certain events.

However, if you have dealt with an event and do not want it to propagate in this way you can flag this by calling .accept() on the event.

Alternatively, if you do want it to propagate calling .ignore() will achieve this.

python

In this section we've covered signals, slots and events. We've demonstratedsome simple signals, including how to pass less and more data using lambdas.We've created custom signals, and shown how to intercept events, pass onevent handling and use .accept() and .ignore() to hide/show eventsto the UI-parent widget. In the next section we will go on to takea look at two common features of the GUI — toolbars and menus.

Signals are a neat feature of Qt that allow you to pass messages between different components in your applications.

Signals are connected to slots which are functions (or methods) which will be run every time the signal fires. Many signals also transmit data, providing information about the state change or widget that fired them. The receiving slot can use this data to perform different actions in response to the same signal.

However, there is a limitation: the signal can only emit the data it was designed to. So for example, a QAction has a .triggered that fires when that particular action has been activated. The triggered signal emits a single piece of data -- the checked state of the action after being triggered.

For non-checkable actions, this value will always be False

The receiving function does not know whichQAction triggered it, or receiving any other data about it.

This is usually fine. You can tie a particular action to a unique function which does precisely what that action requires. Sometimes however you need the slot function to know more than that QAction is giving it. This could be the object the signal was triggered on, or some other associated metadata which your slot needs to perform the intended result of the signal.

This is a powerful way to extend or modify the built-in signals provided by Qt.

Intercepting the signal

Instead of connecting signal directly to the target function, youinstead use an intermediate function to intercept the signal, modify the signal data and forward that on to your actual slot function.

This slot function must accept the value sent by the signal (here the checked state) and then call the real slot, passing any additional data with the arguments.

Rather than defining this intermediate function, you can also achieve the same thing using a lambda function. As above, this accepts a single parameter checked and then calls the real slot.

python

In both examples the <additional args> can be replaced with anything you want to forward to your slot. In the example below we're forwarding the QAction object action to the receiving slot.

Our handle_trigger slot method will receive both the original checked value and the QAction object. Or receiving slot can look something like this

Pyqt5
python

Below are a few examples using this approach to modify the data sent with the MainWindow.windowTitleChanged signal.

  • PyQt5
  • PySide2

The .setWindowTitle call at the end of the __init__ block changes the window title and triggers the .windowTitleChanged signal, which emits the new window title as a str. We've attached a series of intermediate slot functions (as lambda functions) which modify this signal and then call our custom slots with different parameters.

Running this produces the following output.

bash

The intermediate functions can be as simple or as complicated as you like -- as well as discarding/adding parameters, you can also perform lookups to modify signals to different values.

In the following example a checkbox signal Qt.Checked or Qt.Unchecked is modified by an intermediate slot into a bool value.

  • PyQt5
  • PySide2

In this example we've connected the .stateChange signal to result in two ways -- a) with a intermediate function which calls the .result method with True or False depending on the signal parameter, and b) with a dictionary lookup within an intermediate lambda.

Running this code will output True or False to the command line each time the state is changed (once for each time we connect to the signal).

QCheckbox triggering 2 slots, with modified signal data

Trouble with loops

Signals And Slots Pyqt5

One of the most common reasons for wanting to connect signals in this way is when you're building a series of objects and connecting signals programmatically in a loop. Unfortunately then things aren't always so simple.

If you try and construct intercepted signals while looping over a variable, and want to pass the loop variable to the receiving slot, you'll hit a problem. For example, in the following code we create a series of buttons, and use a intermediate function to pass the buttons value (0-9) with the pressed signal.

  • PyQt5
  • PySide2

Signals And Slots Example Pyqt5

If you run this you'll see the problem -- no matter which button you click on you get the same number (9) shown on the label. Why 9? It's the last value of the loop.

The problem is the line lambda: self.button_pressed(a) where we pass a to the final button_pressed slot. In this context, a is bound to the loop.

Pyqt5 Custom Signals And Slots

python
Slots

We are not passing the value of a when the button is created, but whatever value a has when the signal fires. Since the signal fires after the loop is completed -- we interact with the UI after it is created -- the value of a for every signal is the final value that a had in the loop: 9.

So clicking any of them will send 9 to button_pressed

The solution is to pass the value in as a (re-)named parameter. This binds the parameter to the value of a at that point in the loop, creating a new, un-connected variable. The loop continues, but the bound variable is not altered.

This ensures the correct value whenever it is called.

Connect Signal And Slot Pyqt5

You don't have to rename the variable, you could also choose to use the same name for the bound value.

python

The important thing is to use named parameters. Putting this into a loop, it would look like this:

Running this now, you will see the expected behavior -- with the label updating to a number matching the button which is pressed.

The working code is as follows:

Pyqt5 New Style Signals And Slots

  • PyQt5
  • PySide2
Comments are closed.