问题
In my code I emit a signal (mySignal) and I want to wait for the end of a connected slot (mySlot) execution before it continues:
emit mySignal();
// Wait for the end of mySlot execution...
// Some code that has to be executed only after the end of mySlot execution...
Is there a way to do so ?
回答1:
If the sender and the receiver are in the same thread use Qt::DirectConnection
, if they are in 2 different threads use Qt::BlockingQueuedConnection
.
ClassA a;
ClassB b;
ClassC c;
c.moveToThread(aThread);
QObject::connect(&a, &ClassA::signal, &b, &ClassB::slot, Qt::DirectConnection);
QObject::connect(&a, &ClassA::signal, &c, &ClassC::slot, Qt::BlockingQueuedConnection);
Please note that you will have to disconnect/reconnect if:
- the sender and the receiver end up the the same thread and they previously were not,or you will have a dead lock.
- the sender or the receiver end up in 2 different threads and they previously were in the same thread.
Also Qt::DirectConnection
is the default if the sender and receiver are in the same thread (see Qt::AutoConnection).
来源:https://stackoverflow.com/questions/41985034/wait-for-a-slot-to-finish-the-execution-with-qt