How Qt Handle Events and Signal in Same EventLoop

995 Views Asked by At

I couldn't understand how qt handle events (e.g timer event, socket event etc.) and signals in same event loop.As I understand,timer and socket events are handled via select system call(in Unix like OS).

How an event loop handle signals while sleeping because of select system call.

1

There are 1 best solutions below

3
Vladimir Bershov On

In Qt, signals are used to call slots. When you emit a signal, there are, roughly speaking, only 2 options for calling the corresponding slot:

  1. Direct slot call. This can be thought of as replacing a line with a signal emitting by a line with just a slot call. An event loop is not used to process this signal itself.
  2. Delayed slot call. In this case, the signal will be converted to an event, and the event will be posted to the receiver event loop (the event enqueues in the event loop of the thread the receiver object is living in). From now on, for the processing receiver event loop, it makes no difference whether it was a signal or an event. The event will be picked up by the event loop and will cause the slot invocation sometime later.

From Qt doc: https://doc.qt.io/qt-5/signalsandslots.html#signals

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.

As for understanding an event loop, an event loop is just a loop which process one event from an event queue on each iteration.
In short, this can be represented as follows:

QQueue<QEvent> eventQueue; // Events (and pending slot calls as well) are added to this queue
...

// How an event loop works (schematically):
while(event = eventQueue.dequeue())
{
    do_what_the_event_wants_or_ignore_it(event);
}

Read also https://wiki.qt.io/Threads_Events_QObjects