How to handle events in QThread?

Usually, if I do heavy processing of a process, I can call QCoreApplication::processEvents() or QEventLoop::processEvents() to make sure that my processing does not block other signals and slots.

However, if I create a new QThread and move the worker to this thread, then I do not have QCoreApplication or QEventLoop with which to call processEvents() .

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

However, I cannot figure out how to do this. I suppose this 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 where I try to run a loop has some kind of problem. But even if it worked, how would I call processEvents() on this QEventLoop() ?

As an alternative, QThread also has a setEventDispatcher() function, and QAbstractEventDispatcher has a processEvents() function, but I cannot find anything like this subclass of QAbstractEventDispatcher .

What is the correct way to handle events during an intensive working function on QThread ?

+6
source share
2 answers

According to the documentation, a call to QCoreApplication::processEvents() handles events for any thread that it calls.

+13
source

However, if I create a new QThread and move the worker to this thread, then I do not have QCoreApplication or << 22> with which you can call processEvents() .

Exactly - don't call it. You do not need it, you do not want it.

-6
source

Source: https://habr.com/ru/post/949479/


All Articles