Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Connecting slots and signals for QThreads
geageagea last edited by
I know there are a lot of topics discussing this issue but I still don't understand how QThread and signals must be used.
I have 3 classes subclassing Qthread (DeviceManager, NetworkManager and ModemDriver) and I want to connect them with signals. The DeviceManager object communicates with the NetworkManager object and this one with two ModemDriver objects. Using the QThread::currentThreadId() method, I can see that when the NetworkManager object send a signal, the Thread Id of the receiver's DeviceManager object is not the same as the one executing a while(true) in the run() method. The slot connected to this signal should send another signal to the NetworkManager object, but it never does.
I've tried doing the connect with Qt::QueuedConnection with the same result. I think the problem is that the signal arrives to "another" thread.
My code should have one independent DeviceManager thread, one NetworkManager thread and two ModemDriver threads sending and receiving signals and executing the code of the receiver's thread. Anyone can help me or has any working example similar to my needs?
I hope I made myself clear.
Thanks in advance
2 important points:
- A QThread is not a thread. It is an object that manages a thread.
- Usually, a QThread object lives in the main thread, but runs QThread::run() in a different thread.
In your case, since you want a permanent managers/drivers that use signals and slots, you should use worker-objects instead of subclassing QThread.
Read these pages for more insight:
- "QObject class reference -- Thread Affinity":http://doc-snapshot.qt-project.org/qt5-stable/qobject.html#thread-affinity
- "QThread class reference":http://doc-snapshot.qt-project.org/qt5-stable/qthread.html#details (see the first example about using a worker object)
- "Multithreading Technologies in Qt":http://doc-snapshot.qt-project.org/qt5-stable/threads-technologies.html (See the 3rd example at the bottom of the page: "Have an object living in another thread that can perform different tasks upon request and/or can receive new data to work with."