c++ - 如何处理 QThread 上的事件?

标签 c++ multithreading qt events

通常,如果我在处理密集型函数中,我可以调用 QCoreApplication::processEvents()QEventLoop::processEvents() 以确保我的处理不会阻止其他信号和插槽。

但是,如果我创建一个新的 QThread 并将一个 worker 移动到该线程,那么我就没有 QCoreApplicationQEventLoop 调用 processEvents()

根据我的研究,似乎我应该能够在我创建的新 QThread 上安装一个 QEventLoop,然后我可以调用 processEvents() 在那个 QEventLoop 上。

但是,我不知道该怎么做。我认为它可能看起来像这样:

QThread *thread = new QThread(this);
Worker *worker = new Worker(this);
QEventLoop *loop = new QEventLoop();

connect(thread, SIGNAL(finished()), worker, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
connect(thread, SIGNAL(started()), worker, SLOT(startProcessing()));
connect(worker, SIGNAL(done()), thread, SLOT(quit()));
connect(worker, SIGNAL(done()), loop, SLOT(quit()));

worker->moveToThread(thread);    

//loop->exec() // blocks processing of this thread
loop->moveToThread(thread);

//loop->exec() // loop is not a member of this thread anymore and even
               // if it was, this would block the thread from starting
thread->start();
//loop->exec(); // loop is not a member of this thread anymore and even
                // if it was, this would block this thread from continuing

我尝试开始循环的每个地方都有一些问题。但是,即使这样的事情可行,我如何在 QEventLoop() 上调用 processEvents()

或者,QThread 也有一个函数 setEventDispatcher()QAbstractEventDispatcher 有一个 processEvents() 函数,但我似乎找不到任何子类QAbstractEventDispatcher

QThread 上的密集工作函数期间处理事件的正确方法是什么?

最佳答案

根据文档,调用 QCoreApplication::processEvents() 为调用它的线程处理事件。

关于c++ - 如何处理 QThread 上的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17658811/

相关文章:

java - session 范围的支持 bean 是否必须以线程安全的方式实现?

java - Web应用程序中的线程安全

Qt Creator-意见和想法

c++ - 尽管在 make 文件中添加了多媒体,但找不到 QT QMediaPlayer

c++ - C/C++中函数main()的地址

c++ - 如何使用 x264 API 将图片编码为 H264?

java - 如何取消 SwingWorker 的执行?

c++ - 在 QPixmap 中写入文本

c++ - 如何在vc++ win32 api中控制滚动条

c++ - initwindow 使程序崩溃