In the Qt
document it is said:
if several slots are connected to one signal, the slots will be executed one after the other, in the order they have been connected, when the signal is emitted.
But in the connect()
function, setting the Qt::ConnectionType
type as Qt::QueuedConnection
means "The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread." and Qt::DirectConnection
means "the slot is invoked immediately, when the signal is emitted."
The slots maybe not execute in order.
Are they conflicting?
emit operate(); simply calls operate() method, doesn't matter whether it is declared as signal or not. If it is declared as signal, then the generated (see moc tool) implementation in operate() is executed and connected slots are called.
In Qt, we have an alternative to the callback technique: We use signals and slots. A signal is emitted when a particular event occurs. Qt's widgets have many predefined signals, but we can always subclass widgets to add our own signals to them. A slot is a function that is called in response to a particular signal.
So in normal cases, it will be synchronous and blocking, and with queued connections it will be asynchronous and non-blocking.
Queued Connection The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread. Blocking Queued Connection The slot is invoked as for the Queued Connection, except the current thread blocks until the slot returns.
If multiple slots have a Qt::DirectConnection
, they will be invoked in the order they were connected. If multiple slots have a Qt::QueueConnection
, they will be invoked in the order they were connected. If you mix and match, then all Qt::DirectionConnection
slots will invoke in order, then when control returns to event loop, all the Qt::QueuedConnection
slots will invoke in order.
Note, though, that even though the slot invocation order is known, depending on it will almost always lead to brittle code. Connections are meant to be dynamic. It's rather hard for them to be dynamic when you depend on the order of connections remaining static. If you have code that really depends on the connection order, you should refactor it so that the order of execution is controlled some other way, or otherwise it is made known to the maintainer of the code that the actions need to be sequenced.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With