Qt Signal Slot Queued Connection

Posted on  by admin
Qt-UI

A direct connection means that the slot is always invoked directly by the thread the signal is emitted from; a queued connection means that an event is posted in the event queue of the thread the receiver is living in, which will be picked up by the event loop and will cause the slot invocation sometime later. Hence in the absence of a wrapper that would store a copy (or a shared pointer), a queued slot connection could wind up using the bad data. But it was raised to my attention by @BenjaminT and @cgmb that Qt actually does have special handling for const reference parameters.

Queued Connections

‹ Scoped Lock ● Producer Consumer Example ›

Signal

How to pass the produced soup to a consumer, e.g. to the main thread?

Passing messages between threads is easy with Qt. We simply pass objects through a signal/slot connection via so called queued connections.

Qt Signal Slot Queued Connection Settings

Passing a message through a regular slot is done via parametrization:

message sender:

Signal

message receiver:

Then the receiver is invoked from the same thread as the sender.

Qt Signal Slot Queued Connection Tool

To invoke the receiver on a different thread, we connect the signal and the slot with the option of a queued connection:

connect(sender, SIGNAL(signal(QString &)),
receiver, SLOT(slot(QString &)),
Qt::QueuedConnection);
Qt Signal Slot Queued Connection

Then a triggered signal in the sender thread has the effect of a copy of the parameters being stored in the event queue. The sender returns immediately after the copy has been posted. The copy is delivered to the receiver when the receiver thread yields to the event loop.

This scheme works as long as

Qt Signal Slot Queued Connection

Qt Signal Slot Queued Connection Download

  • The type of the passed parameters is a class with a copy constructor.
  • Either the sender or the receiver have an event loop running.
  • The type of the parameter is known to Qt.

If the data type is unknown we register it before connecting the respective signal:

Qt Signal Slot Queued Connections


Qt Signal Slot Queuedconnection

Signal

‹ Scoped Lock ● Producer Consumer Example ›