22

If I had a class A, where one of its functions does:

void A::func()
{
    emit first_signal();
    emit second_signal();
}

Assuming that a class B has 2 slots, one connected to first_signal, and the other to second_signal, is it guaranteed that the slot that is connected to first_signal will always be processed before the second_signal slot?

Marc Mutz - mmutz
  • 24,485
  • 12
  • 80
  • 90
sivabudh
  • 31,807
  • 63
  • 162
  • 228

1 Answers1

16

If you use direct connection type between signals and slots (Qt::DirectConnection) then the answer is yes.

From Qt help system:

When a signal is emitted, the slots connected to it are usually executed immediately, just like a normal function call. When this happens, the signals and slots mechanism is totally independent of any GUI event loop. Execution of the code following the emit statement will occur once all slots have returned. The situation is slightly different when using queued connections; in such a case, the code following the emit keyword will continue immediately, and the slots will be executed later.

You can change default connection type to any of enum Qt::ConnectionType in QObject::connect method.

Christophe Weis
  • 2,518
  • 4
  • 28
  • 32
Wildcat
  • 8,701
  • 6
  • 42
  • 63
  • 1
    I think that it would be guaranteed as long as they have the same type, even if it isn't default. The queued one would create two events, each with the same priority, and those events would then be processed in order. Also, the default connection type is Qt::AutoConnection, which resolves to direct as long as both emitter and receiver are in the same thread. – Caleb Huitt - cjhuitt Nov 14 '09 at 14:03
  • 3
    Your post's beginning sentence should read `If you use DIRECT connection type between signals and slots`; since default type is `Qt::AutoConnection` which behaves differently depending on whether or not the sending code and the receiving object live in different threads. See [`Qt::ConnectionType` docs](http://qt-project.org/doc/qt-4.8/qt.html#ConnectionType-enum) and [Threads, Events and QObjects](http://qt-project.org/wiki/Threads_Events_QObjects). – Hossein May 10 '13 at 07:01
  • 5
    If you chose Qt::QueuedConnection (or Qt::AutoConnection and the slot was in a different thread to the signal), of course the slot would be called asynchronously, but I think the question still stands "Is it guaranteed that the slot that is connected to first_signal will always be processed before the second_signal slot?" Anyone got an answer? – Paul Masri-Stone Jan 15 '16 at 10:45