Qt: Correct way to post events to a QThread?

后端 未结 2 2056
时光说笑
时光说笑 2021-02-19 08:13

In my Qt application, I have a main thread and a worker thread. The worker thread subclasses QThread and processes events via customEvent. Is this the

相关标签:
2条回答
  • 2021-02-19 08:42

    Your understanding is correct and is indeed very unintuitive :)

    A lot of the trouble comes from the documentation for QThread that suggests subclassing QThread. Although Qthread has its own event loop, only events and signals for QObjects created in the run() method (created in that thread) will be processed in the QThread event loop.

    It is much better to encapsulate your thread logic in a QObject subclass and then move that object to an instance of a plain QThread. You can then communicate with that QObject using signals (which will be correctly queued across thread boundaries) or custom events.

    There are some links in this similar question that should help.

    0 讨论(0)
  • 2021-02-19 08:42

    Events are processed by the main event loop, which lives in QApplication or QCoreApplication. So it does not make sense to send events to QObjects in other threads (unless you create another event loop there which I am not sure is possible).

    You can send events from other threads to your main thread, though. The myWorkerThread in your example is owned by the main thread, because it is created there. Objects created by your worker thread in run() and below are owned by this thread.

    You also can send signals to slots in other thread, for example if you want to draw a widget (which must be done in the main thread) from your worker thread or similar.

    0 讨论(0)
提交回复
热议问题