4

Currently I am creating a thread.
If that thread wants to communicate with the main thread in order to interact with the GUI, It emits signals that are connected to slots on the main widget thread.This works all fine.
However for this solution I have to go back to my original GUI form and add slots to it.

I wanted to know if I could simply do this using lambda functions. For instance in the following example class foo is launched on a separate thread. Like this

QObject::connect(this,&myclass::someSignal,
                 [](std::string msg)
                 {
                     QMessageBox::information(mptr,"Some title",
                     msg.c_str(),QMessageBox::StandardButton::Ok);
                 });

This gives an error that Widget must be created in GUI thread. And I understand that.

I wanted to know if there was a way for me to specify to run this slot on mptr instance. Like we do using the old Qt QObject::connect signal slot parameter

ymoreau
  • 3,402
  • 1
  • 22
  • 60
Rajeshwar
  • 11,179
  • 26
  • 86
  • 158

1 Answers1

0

Just like the classic signal/slot connection where you specify the sender and the receiver, you can specify a QObject context to connect to a lambda :

QObject::connect(this, &myclass::someSignal,
                 mptr, // Slot/lambda will be executed in this QObject's context
                 [](std::string msg)
                 {
                     QMessageBox::information(mptr,"Some title",
                     msg.c_str(),QMessageBox::StandardButton::Ok);
                 });

Meaning that the slot/lambda will be queued in the event loop of the context you specify :
https://doc.qt.io/qt-5/qobject.html#connect-5

ymoreau
  • 3,402
  • 1
  • 22
  • 60