0

I have read the doc of Qt and have the following question: if I have:

class_A::on_button_click(){
...do some things...//no signal emit this part

emit signal_A();
}

class_B::on_signal_received(){
...do some things...//no signal emit this part
}

...
connect(class_A_object,SIGNAL(signal_A()),class_B_object,on_signal_received);

All the things here are in the main thread, now when I click the button and trigger the first function,

the program will be executed from the first line of

class_A::on_button_click()

until the last line of

class_B::on_signal_received() 

and during the process nothing else in the main thread will get the chance to be executed, is this correct?( "...do some things..." part don't emit any signals)

In other words, when is the moment that the control return to the event loop? After finishing

class_A::on_button_click()

or

class_B::on_signal_received()

?

Nyaruko
  • 4,329
  • 9
  • 54
  • 105
  • 1
    From qt doc, if signal slot are in the same thread, connection type will be direct. And you r understanding is correct, you can verify this by inspect the call stack by setting a break point inside function on_signal_received(). The control return to event loop after on_button_click(). – m. c. Dec 12 '14 at 18:57
  • So the sequence is: 1. click 2. on_button_click() 3. emit signal 4. on_signal_received() 5. return to on_button_click() 6. finish, return to event loop? – Nyaruko Dec 12 '14 at 19:58
  • I think you are right, again, you can set a break point at on_signal_received(), then inspect the call stack. – m. c. Dec 12 '14 at 20:06

1 Answers1

1

When your signal and slot are in the same thread (as mentioned by user3183610) your signal will be direct connection (the default for same-thread). This effectively runs similarly to a function call. The signal is not queued, but instead the slot that the signal is connected to executes immediately - so you can think of it as a direct function call to the slot.

You can, however, change this behavior by using the Qt::QueuedConnection optional parameter at the end of your connect call:

connect(class_A_object,SIGNAL(signal_A()),class_B_object,on_signal_received, Qt::QueuedConnection);

This will force the use of the queue, your signal will be queued in the event loop and then other pending signals will be executed in order (this is often more desirable then DirectConnection because you can more easily guarantee the order of events). I tend towards to use of queued connections for this reason (though I believe direct is very slightly more efficient).

So for your code there is no return to the event loop until after on_button_click(). During on_button_click() you emit the diret signal signal_x() and immediately on_signal_received() is called (by-passing the event loop), when this finishes it returns back to on_button_click() - just like a function call would :)

code_fodder
  • 15,263
  • 17
  • 90
  • 167