Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt - emit a signal from a c++ thread

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

How can I do it?

like image 977
Mohammad Reza Ramezani Avatar asked Jul 27 '14 15:07

Mohammad Reza Ramezani


1 Answers

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.

like image 97
jpo38 Avatar answered Sep 28 '22 00:09

jpo38