Qt Signal Slot Queued Connection

4/9/2022by admin
Signal

Demonstrates multi-thread programming using Qt.

A developer can choose to connect to a signal by creating a function (a 'slot') and calling the connect function to relate the signal to the slot. Qt's signals and slots mechanism does not require classes to have knowledge of each other, which makes it much easier to develop highly reusable classes.

Contents:

Overview

In the Custom Type Example, we showed how to integrate custom types with the meta-object system, enabling them to be stored in QVariant objects, written out in debugging information and used in signal-slot communication.

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. The signals and slots mechanism is a central feature of Qt. In GUI programming, when we change one widget, we often want another widget to be notified. More generally, we want objects of any kind to be able to communicate with one another. Signals are emitted by objects when they change their state in a way that may be interesting to other objects. Hence in the absence of a wrapper that would store a copy (or a shared pointer), a queued slot connection could wind up using the bad data. But it was raised to my attention by @BenjaminT and @cgmb that Qt actually does have special handling for const reference parameters.

In this example, we create a new value class, Block, and register it with the meta-object system to enable us to send instances of it between threads using queued signals and slots.

The Block Class

The Block class is similar to the Message class described in the Custom Type Example. It provides the default constructor, copy constructor and destructor in the public section of the class that the meta-object system requires. It describes a colored rectangle.

We will still need to register it with the meta-object system at run-time by calling the qRegisterMetaType() template function before we make any signal-slot connections that use this type. Even though we do not intend to use the type with QVariant in this example, it is good practice to also declare the new type with Q_DECLARE_METATYPE().

The implementation of the Block class is trivial, so we avoid quoting it here.

The Window Class

We define a simple Window class with a public slot that accepts a Block object. The rest of the class is concerned with managing the user interface and handling images.

The Window class also contains a worker thread, provided by a RenderThread object. This will emit signals to send Block objects to the window's addBlock(Block) slot.

The parts of the Window class that are most relevant are the constructor and the addBlock(Block) slot.

The constructor creates a thread for rendering images, sets up a user interface containing a label and two push buttons that are connected to slots in the same class.

In the last of these connections, we connect a signal in the RenderThread object to the addBlock(Block) slot in the window.

The rest of the constructor simply sets up the layout of the window.

The addBlock(Block) slot receives blocks from the rendering thread via the signal-slot connection set up in the constructor:

We simply paint these onto the label as they arrive.

The RenderThread Class

The RenderThread class processes an image, creating Block objects and using the sendBlock(Block) signal to send them to other components in the example.

The constructor and destructor are not quoted here. These take care of setting up the thread's internal state and cleaning up when it is destroyed.

Processing is started with the processImage() function, which calls the RenderThread class's reimplementation of the QThread::run() function:

Ignoring the details of the way the image is processed, we see that the signal containing a block is emitted in the usual way:

Each signal that is emitted will be queued and delivered later to the window's addBlock(Block) slot.

Registering the Type

ConnectionSignal

In the example's main() function, we perform the registration of the Block class as a custom type with the meta-object system by calling the qRegisterMetaType() template function:

This call is placed here to ensure that the type is registered before any signal-slot connections are made that use it.

The rest of the main() function is concerned with setting a seed for the pseudo-random number generator, creating and showing the window, and setting a default image. See the source code for the implementation of the createImage() function.

Further Reading

Qt signal slot queued connection tool

This example showed how a custom type can be registered with the meta-object system so that it can be used with signal-slot connections between threads. For ordinary communication involving direct signals and slots, it is enough to simply declare the type in the way described in the Custom Type Example.

In practice, both the Q_DECLARE_METATYPE() macro and the qRegisterMetaType() template function can be used to register custom types, but qRegisterMetaType() is only required if you need to perform signal-slot communication or need to create and destroy objects of the custom type at run-time.

More information on using custom types with Qt can be found in the Creating Custom Qt Types document.

Files:

© 2020 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

QThread inherits QObject. It emits signals to indicate that the thread started or finished executing, and provides a few slots as well.

More interesting is that QObjects can be used in multiple threads, emit signals that invoke slots in other threads, and post events to objects that 'live' in other threads. This is possible because each thread is allowed to have its own event loop.

QObject Reentrancy

QObject is reentrant. Most of its non-GUI subclasses, such as QTimer, QTcpSocket, QUdpSocket and QProcess, are also reentrant, making it possible to use these classes from multiple threads simultaneously. Note that these classes are designed to be created and used from within a single thread; creating an object in one thread and calling its functions from another thread is not guaranteed to work. There are three constraints to be aware of:

  • The child of a QObject must always be created in the thread where the parent was created. This implies, among other things, that you should never pass the QThread object (this) as the parent of an object created in the thread (since the QThread object itself was created in another thread).
  • Event driven objects may only be used in a single thread. Specifically, this applies to the timer mechanism and the network module. For example, you cannot start a timer or connect a socket in a thread that is not the object's thread.
  • You must ensure that all objects created in a thread are deleted before you delete the QThread. This can be done easily by creating the objects on the stack in your run() implementation.

Although QObject is reentrant, the GUI classes, notably QWidget and all its subclasses, are not reentrant. They can only be used from the main thread. As noted earlier, QCoreApplication::exec() must also be called from that thread.

In practice, the impossibility of using GUI classes in other threads than the main thread can easily be worked around by putting time-consuming operations in a separate worker thread and displaying the results on screen in the main thread when the worker thread is finished. This is the approach used for implementing the Mandelbrot Example and the Blocking Fortune Client Example.

Signal

In general, creating QObjects before the QApplication is not supported and can lead to weird crashes on exit, depending on the platform. This means static instances of QObject are also not supported. A properly structured single or multi-threaded application should make the QApplication be the first created, and last destroyed QObject.

Per-Thread Event Loop

Each thread can have its own event loop. The initial thread starts its event loop using QCoreApplication::exec(), or for single-dialog GUI applications, sometimes QDialog::exec(). Other threads can start an event loop using QThread::exec(). Like QCoreApplication, QThread provides an exit(int) function and a quit() slot.

An event loop in a thread makes it possible for the thread to use certain non-GUI Qt classes that require the presence of an event loop (such as QTimer, QTcpSocket, and QProcess). It also makes it possible to connect signals from any threads to slots of a specific thread. This is explained in more detail in the Signals and Slots Across Threads section below.

A QObject instance is said to live in the thread in which it is created. Events to that object are dispatched by that thread's event loop. The thread in which a QObject lives is available using QObject::thread().

The QObject::moveToThread() function changes the thread affinity for an object and its children (the object cannot be moved if it has a parent).

Calling delete on a QObject from a thread other than the one that owns the object (or accessing the object in other ways) is unsafe, unless you guarantee that the object isn't processing events at that moment. Use QObject::deleteLater() instead, and a DeferredDelete event will be posted, which the event loop of the object's thread will eventually pick up. By default, the thread that owns a QObject is the thread that creates the QObject, but not after QObject::moveToThread() has been called.

If no event loop is running, events won't be delivered to the object. For example, if you create a QTimer object in a thread but never call exec(), the QTimer will never emit its timeout() signal. Calling deleteLater() won't work either. (These restrictions apply to the main thread as well.)

You can manually post events to any object in any thread at any time using the thread-safe function QCoreApplication::postEvent(). The events will automatically be dispatched by the event loop of the thread where the object was created.

Event filters are supported in all threads, with the restriction that the monitoring object must live in the same thread as the monitored object. Similarly, QCoreApplication::sendEvent() (unlike postEvent()) can only be used to dispatch events to objects living in the thread from which the function is called.

Accessing QObject Subclasses from Other Threads

QObject and all of its subclasses are not thread-safe. This includes the entire event delivery system. It is important to keep in mind that the event loop may be delivering events to your QObject subclass while you are accessing the object from another thread.

If you are calling a function on an QObject subclass that doesn't live in the current thread and the object might receive events, you must protect all access to your QObject subclass's internal data with a mutex; otherwise, you may experience crashes or other undesired behavior.

Like other objects, QThread objects live in the thread where the object was created -- not in the thread that is created when QThread::run() is called. It is generally unsafe to provide slots in your QThread subclass, unless you protect the member variables with a mutex.

Qt Signal Slot Queued Connection Settings

On the other hand, you can safely emit signals from your QThread::run() implementation, because signal emission is thread-safe.

Signals and Slots Across Threads

Qt supports these signal-slot connection types:

  • Auto Connection (default) If the signal is emitted in the thread which the receiving object has affinity then the behavior is the same as the Direct Connection. Otherwise, the behavior is the same as the Queued Connection.'
  • Direct Connection The slot is invoked immediately, when the signal is emitted. The slot is executed in the emitter's thread, which is not necessarily the receiver's thread.
  • Queued Connection The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.
  • Blocking Queued Connection The slot is invoked as for the Queued Connection, except the current thread blocks until the slot returns.

    Note: Using this type to connect objects in the same thread will cause deadlock.

  • Unique Connection The behavior is the same as the Auto Connection, but the connection is made only if it does not duplicate an existing connection. i.e., if the same signal is already connected to the same slot for the same pair of objects, then the connection is not made and connect() returns false.

Qt Signal Slot Queued Connection Download

The connection type can be specified by passing an additional argument to connect(). Be aware that using direct connections when the sender and receiver live in different threads is unsafe if an event loop is running in the receiver's thread, for the same reason that calling any function on an object living in another thread is unsafe.

QObject::connect() itself is thread-safe.

The Mandelbrot Example uses a queued connection to communicate between a worker thread and the main thread. To avoid freezing the main thread's event loop (and, as a consequence, the application's user interface), all the Mandelbrot fractal computation is done in a separate worker thread. The thread emits a signal when it is done rendering the fractal.

Qt Signal Slot Queued Connection Tool

Similarly, the Blocking Fortune Client Example uses a separate thread for communicating with a TCP server asynchronously.

Qt Signal Slot Queued Connections

© 2020 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

Comments are closed.