Qt - emit a signal from a c++ thread

Mohammad Reza  Ramezani picture Mohammad Reza Ramezani · Jul 27, 2014 · Viewed 10.6k times · Source

I want to emit a signal from a C++ thread (std::thread) in Qt.

How can I do it?

Answer

jpo38 picture jpo38 · Jul 27, 2014

You definitely can emit a signal from a thread (QThread, std::thread or even boost::thread). Only you must be careful of your connect function's fifth parameter (Qt::ConnectionType):

If Qt::DirectConnection: The slot is invoked immediately (from the current thread), when the signal is emitted. If Qt::QueuedConnection: 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.

See ConnectionType-enum for more options.

The problem is not really from which thread you emit the signal, it's more from which thread the slot is being invoked. For instance, I think QLabel::setText must be executed from QLabel's owner thread (most likely main thread). So if you emit a signal connected to a QLabel's setText from a thread, connection must be done with Qt::AutoConnection, Qt::QueuedConnection or Qt::BlockingQueuedConnection.