Pyqt Signals And Slots Across Threads

Posted onby
  • Signals And Slots Across Threads Qt Neteller do not qualify for this bonus offer. The bonus offer is Signals And Slots Across Threads Qt available to players from: Andorra, Gibraltar, Malta, Iceland, Liechtenstein, Monaco and Luxembourg. Players must wager the bonus amounts Signals And Slots Across Threads Qt 35 times. 18+, New Players Only.
  • When a signal is emitted and there's a slot connected to that signal an event is posted in the receiving thread's event loop that the slot should be invoked. Consequently, when the event is processed the slot will be invoked. So you can see that without event loop there's no slots!

PyQt is more versatile than C/Qt in this regard, because we can connect not just to slots, but also to any callable, and from PyQt 4.2, it is possible to dynamically add 'predefined' signals and slots to QObjects. Let's see how signals and slots works in practice with the Signals and Slots program shown in Figure 4.6.

This example was ported from the PyQt4 version by Guðjón Guðjónsson.

Threads

Introduction

In some applications it is often necessary to perform long-running tasks, such as computations or network operations, that cannot be broken up into smaller pieces and processed alongside normal application events. In such cases, we would like to be able to perform these tasks in a way that does not interfere with the normal running of the application, and ensure that the user interface continues to be updated. One way of achieving this is to perform these tasks in a separate thread to the main user interface thread, and only interact with it when we have results we need to display.

This example shows how to create a separate thread to perform a task - in this case, drawing stars for a picture - while continuing to run the main user interface thread. The worker thread draws each star onto its own individual image, and it passes each image back to the example's window which resides in the main application thread.

The User Interface

We begin by importing the modules we require. We need the math and random modules to help us draw stars.

The main window in this example is just a QWidget. We create a single Worker instance that we can reuse as required.

The user interface consists of a label, spin box and a push button that the user interacts with to configure the number of stars that the thread wil draw. The output from the thread is presented in a QLabel instance, viewer.

We connect the standard finished() and terminated() signals from the thread to the same slot in the widget. This will reset the user interface when the thread stops running. The custom output(QRect, QImage) signal is connected to the addImage() slot so that we can update the viewer label every time a new star is drawn.

The start button's clicked() signal is connected to the makePicture() slot, which is responsible for starting the worker thread.

We place each of the widgets into a grid layout and set the window's title:

The makePicture() slot needs to do three things: disable the user interface widgets that are used to start a thread, clear the viewer label with a new pixmap, and start the thread with the appropriate parameters.

Since the start button is the only widget that can cause this slot to be invoked, we simply disable it before starting the thread, avoiding problems with re-entrancy.

We call a custom method in the Worker thread instance with the size of the viewer label and the number of stars, obtained from the spin box.

Whenever is star is drawn by the worker thread, it will emit a signal that is connected to the addImage() slot. This slot is called with a QRect value, indicating where the star should be placed in the pixmap held by the viewer label, and an image of the star itself:

We use a QPainter to draw the image at the appropriate place on the label's pixmap.

The updateUi() slot is called when a thread stops running. Since we usually want to let the user run the thread again, we reset the user interface to enable the start button to be pressed:

Now that we have seen how an instance of the Window class uses the worker thread, let us take a look at the thread's implementation.

The Worker Thread

The worker thread is implemented as a PyQt thread rather than a Python thread since we want to take advantage of the signals and slots mechanism to communicate with the main application.

We define size and stars attributes that store information about the work the thread is required to do, and we assign default values to them. The exiting attribute is used to tell the thread to stop processing.

Each star is drawn using a QPainterPath that we define in advance:

Before a Worker object is destroyed, we need to ensure that it stops processing. For this reason, we implement the following method in a way that indicates to the part of the object that performs the processing that it must stop, and waits until it does so.

For convenience, we define a method to set up the attributes required by the thread before starting it.

The start() method is a special method that sets up the thread and calls our implementation of the run() method. We provide the render() method instead of letting our own run() method take extra arguments because the run() method is called by PyQt itself with no arguments.

The run() method is where we perform the processing that occurs in the thread provided by the Worker instance:

Information stored as attributes in the instance determines the number of stars to be drawn and the area over which they will be distributed.

We draw the number of stars requested as long as the exiting attribute remains False. This additional check allows us to terminate the thread on demand by setting the exiting attribute to True at any time.

The drawing code is not particularly relevant to this example. We simply draw on an appropriately-sized transparent image.

For each star drawn, we send the main thread information about where it should be placed along with the star's image by emitting our custom output() signal:

Since QRect and QImage objects can be serialized for transmission via the signals and slots mechanism, they can be sent between threads in this way, making it convenient to use threads in a wide range of situations where built-in types are used.

Running the Example

We only need one more piece of code to complete the example:

Recently, I was writing an integration test for a data visualization GUI. The GUI calls out to an external process to run a simulation, waits for the simulator to produce data, and reads the data back in to produce pretty graphs, export data to other formats, etc. I use a PySide signal to inform the GUI that the simulator has produced data. Unfortunately, I couldn’t find a clean way to have my integration test wait for that signal. Luckily, I have found the solution, and I’ll explain it here.

Signals and Slots

PySide and PyQt are Python bindings to the Qt GUI and application framework. One killer feature of Qt is the signal & slot system, which is a way for widgets and objects to communicate events to one another.

An object in Qt can send a signal to other subscribed objects. Signals are used to inform other objects that an event has occurred. For example, buttons fire the QPushButton.pressed signal when they are clicked. When you want to handle a button click, you connect the signal to a function. You can create your own signals, and connect them to arbitrary python functions. In my GUI, I have something like the following:

In this code snippet, we create the Simulator and DataReader classes, and connect them together using a signal. The Simulator class is a QObject, so it can send signals. It runs a simulation in a separate process, and then emits the finished signal when it’s done. We also happen to use a button that starts the simulation when clicked. We connect the simulator’s finished signal to the DataReader so it knows when to begin reading data.

The Test

So, how do I test the above code? I want to run the simulator and make sure it has the correct output. I initially wrote a test like this:

What’s wrong here? The assertion line is executed too early; the simulator probably hasn’t even started in the nanoseconds between when I told it to start and when I check the data! How can we solve this issue? I tried a time.sleep() loop that polls if the simulation is complete. This blocks the main GUI thread, and is not a good solution. I also tried similar things using the threading module, but to no avail. It turns out, we can use a new Qt event loop to stop execution.

Pyqt signals and slots across threads crossword

Solution

I figured out that you can call QEventLoop.exec_() to create a nested event loop. That is, our QApplication instance event loop is already running, but calling QEventLoop.exec_() will stop execution using a new event loop until QEventLoop.quit() is called. Here is our modified example test:

We create an event loop that will help us wait for our simulation to complete. When run_simulation() is called, we wait at the loop.exec_() line until finished is emitted. When the simulator finishes, the event loop will exit, and we will advance beyond the loop.exec_() line.

General Solution

There is one problem with this approach. What if simulator.finished is never emitted, like when an error occurs? We would never advance beyond loop.exec_(). If we had this test running on a continuous integration server, we would lock up a job forever until we realized the test never finished!

A solution is to use the QTimer.singleShot() function with a timeout. That means for every time we want to create an event loop, we have to set up the loop, hook up our signals, and create a timer with a suitable timeout in case the signals never fire. Here is a context manager that can handle this for us:

We can use it like this:

Pyqt signals and slots across threads game

Isn’t that great? I think so.

pytest-qt

I run my tests using the pytest library. There is a plugin for pytest called pytest-qt, which comes with a fixture called qtbot. A qtbot is used to handle all of the boilerplate that comes along with testing PySide/PyQt code, like:

  • Setting up a QApplication
  • Simulating mouse clicks and keyboard interaction
  • Closing windows after tests

Pyqt Signals And Slots Across Threads Crossword

Once I figured out how to stop test execution to wait for a signal, I created a pull request to add this functionality to pytest-qt. I created a more general solution that allows multiple signals, or none at all (just wait for a timeout). If you use PySide/PyQt, but you think testing your GUI code is a pain, check out pytest-qt! Take a look at the example in the docs to see how to use pytest-qt to block tests for signals.

Thanks for reading!

Please enable JavaScript to view the comments powered by Disqus.comments powered by

Pyqt Signals And Slots Across Threads Onto

Disqus