Launching a lambda function slot using the QWidgets Thread example

I am currently creating a thread.
If this thread wants to communicate with the main thread in order to interact with the graphical interface, it gives out signals that are connected to the slots in the main widget thread. This works great.
However, for this solution, I need to go back to my original GUI form and add slots to it.

I wanted to know if I can just do this using lambda functions. For example, in the following example, the class fooruns in 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 the widget must be created in the GUI thread. And I understand that.

I wanted to know if there is a way to specify to run this slot on an instance mptr. Just like we used the old Qt signal slotQObject::connect

+4
source share
1 answer

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

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

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

0
source

Source: https://habr.com/ru/post/1530067/


All Articles