Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Qt many slots connected to the same signal, do they invoke in order when emit the signal?

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?

like image 744
Tian Avatar asked Jul 31 '15 17:07

Tian


People also ask

How does emit work in Qt?

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.

How signals and slots work in Qt?

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.

Are Qt signals synchronous?

So in normal cases, it will be synchronous and blocking, and with queued connections it will be asynchronous and non-blocking.

What is queued connection in Qt?

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.


2 Answers

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.

like image 101
MahlerFive Avatar answered Nov 25 '22 04:11

MahlerFive


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.

like image 22
Kuba hasn't forgotten Monica Avatar answered Nov 25 '22 03:11

Kuba hasn't forgotten Monica