Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QT - Understanding following lambda expression for a SLOT

Tags:

qt

I am currently trying to understand the new QT5 signal/slot syntax

connect(sender, &Sender::valueChanged, [=](const QString &newValue) {
       receiver->updateValue("senderValue", newValue);
   });

Now my question is where is the address of the receiver SLOT in the above expression ? I wanted to know this because what happens if a signal is in threadA and the slot is in thread B and I wanted it to be a queued connection ?

like image 767
MistyD Avatar asked Mar 22 '23 09:03

MistyD


1 Answers

A slot is a piece of code, it doesn't "live" in a thread - a thread might run it or not, but the code itself doesn't belong to any thread. (If the slot is a member function, then the Qt object defined as the receiver belongs to a Qt thread - that's a property of the object, not the function.)

In the code you have above, the compiler generates an object that:

  • captures receiver by value ([=])
  • has a function-call operator that can be called with a reference to a const QString.

That object is passed to connect along with the other two arguments. It's not a QObject, so it doesn't have an owning thread in the Qt sense. What you need to make sure of is that:

  • what receiver points to stays alive for as long as that signal is connected
  • receiver->updateValue(...) is thread-safe - it will be called in sender's context/thread.

If receiver->updateValue needs to be called in receiver's thread/context, then do not use that syntax for the connect call, use the one where you specify both sender and receiver, and the connection type.

like image 52
Mat Avatar answered Apr 26 '23 20:04

Mat