How to perform operations with the graphical interface in the main Qt thread?

I have a simple program consisting of two threads:

  • The main GUI thread controlled by Qt QApplication::exec
  • TCP Network Flow Managed boost::asio::io_service

TCP events, such as connecting or receiving data, cause changes to the GUI. Most often this is setTextin QLabel and hiding various widgets. I am currently performing these actions on a TCP client thread, which seems pretty dangerous.

How to place an event in the main topic of Qt? I am looking for a Qt option boost::asio::io_service::strand::postthat sends an event to an event loop boost::asio::io_service.

+5
source share
2 answers

, TCP QObject, QMetaObject:: invokeMethod().

, QObject, , .

, QObject :

class MyQObject : public QObject {
    Q_OBJECT
public: 
    MyObject() : QObject(nullptr) {}
public slots:
    void mySlotName(const QString& message) { ... }
};

TCP-.

#include <QMetaObject>

void TCPClass::onSomeEvent() {
    MyQObject *myQObject = m_object;
    myMessage = QString("TCP event received.");
    QMetaObject::invokeMethod(myQObject
                               , "mySlotName"
                               , Qt::AutoConnection // Can also use any other except DirectConnection
                               , Q_ARG(QString, myMessage)); // And some more args if needed
}

Qt::DirectConnection , TCP, / .

: invokeMethod , , QObject.

+4

QObject, . - .

QObject, - ( GUI) QTimer, . , :

#include <functional>

void dispatchToMainThread(std::function<void()> callback)
{
    // any thread
    QTimer* timer = new QTimer();
    timer->moveToThread(qApp->thread());
    timer->setSingleShot(true);
    QObject::connect(timer, &QTimer::timeout, [=]()
    {
        // main thread
        callback();
        timer->deleteLater();
    });
    QMetaObject::invokeMethod(timer, "start", Qt::QueuedConnection, Q_ARG(int, 0));
}

...
// in a thread...

dispatchToMainThread( [&, pos, rot]{
    setPos(pos);
    setRotation(rot);
});

, .

https://riptutorial.com/qt/example/21783/using-qtimer-to-run-code-on-main-thread

+1

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


All Articles