Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I process events on a QThread?

Normally if I am in a process intensive function I can call QCoreApplication::processEvents() or QEventLoop::processEvents() to ensure that my processing doesn't block other signals and slots.

However, if I create a new QThread and move a worker to that thread, then I don't have a QCoreApplication or a QEventLoop with which to call processEvents().

From my research, it seems that I should be able to install a QEventLoop on the new QThread I created, and then I can call processEvents() on that QEventLoop.

However, I can't figure out how to do this. I figure it might look something like this:

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

Every place I try to start the loop has some sort of issue. But even if something like this worked, how would I call processEvents() on that QEventLoop()?

Alternatively, QThread also has a function setEventDispatcher() and QAbstractEventDispatcher has a processEvents() function, but I can't seem to find anything that subclasses QAbstractEventDispatcher.

What is the proper way to process events during an intensive worker function on a QThread?

like image 884
Cory Klein Avatar asked Jul 15 '13 16:07

Cory Klein


1 Answers

According to the documentation, calling QCoreApplication::processEvents() processes events for whichever thread called it.

like image 62
Dan Milburn Avatar answered Oct 15 '22 21:10

Dan Milburn