Qt Signal Slot Different Threads

broken image


  1. Qt Signals And Slots Tutorial
  2. Qt Signal Slot Not Working
  3. Qt Signal Thread

I can now emit a signal in one thread and receive it in a slot in a different thread. This is hugely useful when you want to, for example, integrate a blocking-happy library into your application. Here's what I'm talking about in pictures: Signals can arrive at any time from the threads, just like any other signal, and the code in the main. The second example in src/examples/two/ focuses only on the Signals & Slots system of this framework. A third example in src/examples/three/ shows usage of the threading architecture + Signals and Slots of this framework completely without using Qt Signals and Slots. System architecture. Usage of the framework. Cross-thread signal-slot connections are implemented by dispatching a QMetaCallEvent to the target object. A QObject instance can be moved to a thread, where it will process its events, such as timer events or slot/method calls. To do work on a thread, first create your own worker class that derives from QObject. Then move it to the thread. It also knows the type of the signal arguments so it can do the proper type conversion. We use ListLeft to only pass the same number as argument as the slot, which allows connecting a signal with many arguments to a slot with less arguments. QObject::connectImpl is the private internal function that will perform the connection.

Qt - Passing custom objects among threads

Details
Category: Programming
Written by Nandan Banerjee
Hits: 13036

Communication between threads in a qt program is essentially done by using signals/slots. This is by far one of the most easiest and stable mode of communication amongst threads of a program.

For example, let us suppose that one thread needs to send an integer value to another thread. All the programmer needs to do is simply create a dispatch signal with two arguments, the thread id and the integer value. Thus, it can be achieved by this simple line –

Similarly, a receive slot with the same arguments needs to be created to receive the signal.

Now, this will work very nicely when one is dealing with the predefined primitive or the qt data types. This is because they are already registered and hence it is not a problem for qt to recognise those data types.

The problem arises when one wants to pass a custom data type (any class or structure that has a public default constructor, a public copy constructor, and a public destructor can be registered). Then, the user defined class or a class defined in a library not part of qt can be passed using signals/slots after registering.

The qRegisterMetaType() function is used to make the type available to non-template based functions, like the queued signal and slot connections.

This is done in the following way –

where name can be any custom data type.

For example, let us take a program which will capture the image from the webcam and display it in a QLabel on the GUI. To achieve this, two approaches can be taken. Run the camera grabbing function in the main UI thread or in a different thread and reducing the work of the UI thread significantly. If it is run in the main UI thread, then the chances of the UI thread not responding is very high. Therefore, it is always desirable make a separate thread and use it instead to run the camera grabbing function.

In this tutorial, we will use the openCV library to grab an image from the webcam and use the signal/slot mechanism to send the image (IplImage type) to the UI thread.

After creating a new qtGUI project, a new class is created (say 'webcamThread') with QThread as its parent class. A run() function is defined and a new signal with the image as the argument is defined.

In the MainWindow file, a slot is defined to handle the signal from the webcamThread. This image is then converted to the QImage format and then displayed in the QLabel. So, a smooth and pleasant webcam feed can be achieved using this.

Qt code for the webcam feed -

Qt Signal Slot Different Threads

The openCV library needs to be present in the system and the paths should be appropriately set.

// webcamthread.h

// webcamthread.cpp

Now the code for the MainWindow. The signals are connected with the slots and the event handlers are defined.

// mainwindow.h

// mainwindow.cpp

In the UI editor, two buttons (Start and Stop) and a label of size 320 by 240 need to be created. Then, just compile and run. So, it can be seen that objects of the class 'IplImage' from the openCV library can be easily passed between the threads just by registering the class.

The one thing that confuses the most people in the beginning is the Signal & Slot mechanism of Qt. But it's actually not that difficult to understand. In general Signals & Slots are used to loosely connect classes. Illustrated by the keyword emit, Signals are used to broadcast a message to all connected Slots. If no Slots are connected, the message 'is lost in the wild'. So a connection between Signals & Slots is like a TCP/IP connection with a few exceptions, but this metaphor will help you to get the principle. A Signal is an outgoing port and a Slot is an input only port and a Signal can be connected to multiple Slots.

For me one of the best thins is, that you don't have to bother with synchronization with different threads. For example you have one QObject that's emitting the Signal and one QObject receiving the Signal via a Slot, but in a different thread. You connect them via QObject::connect(...) and the framework will deal with the synchronization for you. But there is one thing to keep in mind, if you have an object that uses implicitly sharing (like OpenCV's cv::Mat) as parameter, you have to deal with the synchronization yourself.The standard use-case of Signals & Slots is interacting with the UI from the code while remaining responsive. This is nothing more than a specific version of 'communicating between threads'.Another benefit of using them is loosely coupled objects. The QObject emitting the Signal does not know the Slot-QObject and vice versa. This way you are able to connect QObjects that are otherwise only reachable via a full stack of pointer-calls (eg. this->objA->...->objZ->objB->recieveAQString()). Alone this can save you hours of work if someone decides to change some structure, eg. the UI.

Right now I only mentioned Signal- & Slot-methods. But you are not limited to methods - at least on the Slots side. You can use lambda functions and function pointers here. This moves some of the convenience from languages like Python or Swift to C++.

For some demonstrations I will use the following classes:

Using Connections

Threads

The openCV library needs to be present in the system and the paths should be appropriately set.

// webcamthread.h

// webcamthread.cpp

Now the code for the MainWindow. The signals are connected with the slots and the event handlers are defined.

// mainwindow.h

// mainwindow.cpp

In the UI editor, two buttons (Start and Stop) and a label of size 320 by 240 need to be created. Then, just compile and run. So, it can be seen that objects of the class 'IplImage' from the openCV library can be easily passed between the threads just by registering the class.

The one thing that confuses the most people in the beginning is the Signal & Slot mechanism of Qt. But it's actually not that difficult to understand. In general Signals & Slots are used to loosely connect classes. Illustrated by the keyword emit, Signals are used to broadcast a message to all connected Slots. If no Slots are connected, the message 'is lost in the wild'. So a connection between Signals & Slots is like a TCP/IP connection with a few exceptions, but this metaphor will help you to get the principle. A Signal is an outgoing port and a Slot is an input only port and a Signal can be connected to multiple Slots.

For me one of the best thins is, that you don't have to bother with synchronization with different threads. For example you have one QObject that's emitting the Signal and one QObject receiving the Signal via a Slot, but in a different thread. You connect them via QObject::connect(...) and the framework will deal with the synchronization for you. But there is one thing to keep in mind, if you have an object that uses implicitly sharing (like OpenCV's cv::Mat) as parameter, you have to deal with the synchronization yourself.The standard use-case of Signals & Slots is interacting with the UI from the code while remaining responsive. This is nothing more than a specific version of 'communicating between threads'.Another benefit of using them is loosely coupled objects. The QObject emitting the Signal does not know the Slot-QObject and vice versa. This way you are able to connect QObjects that are otherwise only reachable via a full stack of pointer-calls (eg. this->objA->...->objZ->objB->recieveAQString()). Alone this can save you hours of work if someone decides to change some structure, eg. the UI.

Right now I only mentioned Signal- & Slot-methods. But you are not limited to methods - at least on the Slots side. You can use lambda functions and function pointers here. This moves some of the convenience from languages like Python or Swift to C++.

For some demonstrations I will use the following classes:

Using Connections

Qt Signals And Slots Tutorial

To connect a Signal to a Slot you can simply call QObject::connect(a, &AObject::signalSometing, b, &BObject::recieveAQString) or QObject::connect(a, SIGNAL(signalSometing(QString), b, SLOT(recieveAQString(QString)) if you want to use the 'old' syntax. The main difference is, if you use the new syntax, you have compile-time type-checking and -converting. But one big advantage of the 'old' method is that you don't need to bother with inheritance and select the most specialized method.Lambdas can be a very efficient way of using Signals & Slots. If you just want to print the value, e.g. if the corresponding property changes, the most efficient way is to use lambdas. So by using lambdas you don't have to blow up your classes with simple methods. But be aware, that if you manipulate any object inside the lambda you have to keep in mind, that synchronization issues (in a multithreaded environment) might occur.

You will get an idea of how to use the different methods in the following example:

As you see, recived a QString: 'Hello' is printed two times. This happens because we connected the same Signals & Slots two times (using different methods). In the case, you don't want that, you see some methods to prohibit that and other options in the next section Connection Types.

One side note: if you are using Qt::QueuedConnection and your program looks like the following example, at some point you will probably wonder, why calling the Signal will not call the Slots until app.exec() is called. The reason for this behavior is that the event queue, the Slot-call is enqueued, will start with this call (and block until program exits).

And before we start with the next section here is a little trick to call a method of another thread inside the context of the other thread. This means, that the method will be executed by the other thread and not by the 'calling' one.

To learn more about that here is your source of truth: https://doc.qt.io/qt-5/qmetamethod.html#invoke

Connection Types

Qt::AutoConnection

Qt::AutoConnection is the default value for any QObject::connect(...) call. If both QObjects that are about to be connected are in the same thread, a Qt::DirectConnection is used. But if one is in another thread, a Qt::QueuedConnection is used instead to ensure thread-safety. Please keep in mind, if you have both QObjects in the same thread and connected them the connection type is Qt::DirectConnection, even if you move one QObject to another thread afterwards. I generally use Qt::QueuedConnection explicitly if I know that the QObjects are in different threads.

Qt::DirectConnection

A Qt::DirectConnection is the connection with the most minimal overhead you can get with Signals & Slots. You can visualize it that way: If you call the Signal the method generated by Qt for you calls all Slots in place and then returns.

Qt::QueuedConnection

Qt Signal Slot Not Working

The Qt::QueuedConnection will ensure that the Slot is called in the thread of the corresponding QObject. It uses the fact, that every thread in Qt (QThread) has a Event-queue by default. So if you call the Signal of the QObject the method generated by Qt will enqueue the command to call the Slot in the Event-queue of the other QObjects thread. The Signal-method returns immediately after enqueuing the command. To ensure all parameters exist within the other threads scope, they have to be copied. The meta-object system of Qt has to know all of the parameter types to be capable of that (see qRegisterMetaType).

Qt Signal Thread

Qt::BlockingQueuedConnection

A Qt::BlockingQueuedConnection is like a Qt::QueuedConnection but the Signal-method will block until the Slot returns. If you use this connection type on QObjects that are in the same thread you will have a deadlock. And no one likes deadlocks (at least I don't know anyone).

Qt::UniqueConnection

Qt::UniqueConnection is not really a connection type but a modifier. If you use this flag you are not able to connect the same connection again. But if you try it QObject::connect(...) will fail and return false.

This is not everything you will ever need to know about Signals & Slots but with this information you can cover about 80% of all use-cases (in my opinion).If it happens and you need the other 20% of information, I'll give you some good links to search your specific problem on:

The Qt documentation:

Very deep understanding:

Part1: https://woboq.com/blog/how-qt-signals-slots-work.html

Part2: https://woboq.com/blog/how-qt-signals-slots-work-part2-qt5.html

Part3: https://woboq.com/blog/how-qt-signals-slots-work-part3-queuedconnection.html

< previous step | index | next step >





broken image