Qt Using QTimer to run code on main thread


Example

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));
}

This is useful when you need to update a UI element from a thread. Keep in mind lifetime of anything the callback references.

DispatchToMainThread([]
{
    // main thread
    // do UI work here
});

Same code could be adapted to run code on any thread that runs Qt event loop, thus implementing a simple dispatch mechanism.