Wait for a SLOT to finish the execution with Qt
Asked Answered
C

1

5

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 ?

Condottiere answered 1/2, 2017 at 16:41 Comment(2)
Do the signal and connected slot belong to objects in the same thread? If so, this will happen anyway. If not, the Qt approach is not to wait, but to emit another signal at the end of the connected slot, which causes the remainder of the code to run.Palatalized
You're probably better off with a standard callback function in these types of cases rather than invoking the overhead of Qt's signals and slots.Mamie
W
10

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).

Whitton answered 2/2, 2017 at 8:38 Comment(3)
I have a single threaded App, which is used for socket read write. Whenever the data is received on socket, in the same function data is written for ACK. However, it seems that many a times the data received in between when the slot is still getting executed. The function is not yet completed and this leads to a recursive hierarchy which crashes later on. Is there any solution for this?Ubiquitous
@Ubiquitous You should ask your own question. And describe what you mean by "the data received in between when the slot is still getting executed" it is not clearWhitton
Please refer: Why a new signal for socket::readyRead() is served even when its earlier slot is still executing?. Have typed from mobile, excuse me for any bad formats.Ubiquitous

© 2022 - 2024 — McMap. All rights reserved.