Qt:将事件发布到QThread的正确方法? [英] Qt: Correct way to post events to a QThread?

查看:160
本文介绍了Qt:将事件发布到QThread的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Qt应用程序中,我有一个主线程和一个工作线程。工作线程子类 QThread 并通过 customEvent 处理事件。这是主线程发送要由工作线程处理的事件的正确方法吗?

  QThread * myWorkerThread = // ... 

QApplication :: instance() - > postEvent(myWorkerThread,new MyWorkRequestEvent(/ * ... * /);

如果我正确阅读文档,它表示事件在拥有事件收件人的对象的线程上被处理,因为 QThread 由主线程创建,它由主线程拥有 - 所以这个事件将被主线程处理(这将是反直觉的,在我的情况下会是错误的)? p>

解决方案

您的理解是正确的,确实非常不直观:)



很多麻烦来自QThread的文档,建议对QThread进行子类化。虽然Qthread有自己的事件循环,只有在run()方法(在该线程中创建)中创建的QObjects的事件和信号将在QThread事件循环中处理。



将你的线程逻辑封装在一个QObject子类中,然后将该对象移动到一个纯QThread的一个实例上是更好的了。然后,您可以使用信号(将通过线程边界正确排队)或自定义事件与该QObject通信。



类似的问题,应该有帮助。


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 correct way for the main thread to send events to be processed by the worker thread?

QThread* myWorkerThread = // ...

QApplication::instance()->postEvent (myWorkerThread, new MyWorkRequestEvent(/* ... */);

If I read the documentation correctly, it states that events are processed on the thread of the object that own the event recipient. Since QThread was created by the main thread, it is owned by the main thread -- so would this event be processed by the main thread (which would be counter-intuitive, and in my case would be wrong)?

解决方案

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.

这篇关于Qt:将事件发布到QThread的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆