如何在QThread上处理事件

How do I process events on a QThread?

本文关键字:处理事件 QThread      更新时间:2023-10-16

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

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

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

然而,我不知道该怎么做。我想它可能看起来像这样:

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()会处理调用它的线程的事件。

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

没错-不要叫它。你不需要它,你不想要它。