Qt - emit a signal from a c++ thread

后端 未结 4 685
孤独总比滥情好
孤独总比滥情好 2021-01-01 20:04

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

How can I do it?

4条回答
  •  Happy的楠姐
    2021-01-01 20:51

    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.

提交回复
热议问题