Search code examples
c++multithreadingqtqthread

Invoking a function on a QThread that is already running


I have seen a lot of examples on the internet (and the Qt documentation) where to use QThread, a subclass of the class is made and then a worker object is moved to that thread. Then essentially the QThread::started() signal is connected to some slot of the worker class object to run a certain function. Now I would like to do the same in my project, the difference being I would like to move my worker class to a thread that is already running and then call some function on that thread. To achieve this I came up with a slight hack like in the code below, where I use the QTimer class to invoke a public slot in my worker class.

    QThread myThread;
    myThread.setObjectName("myThread");
    myThread.start();

    Worker worker;
    worker.moveToThread(&myThread);

    QTimer::singleShot(0, &worker, [&worker](){
        worker.doStuff(5);
    });

Is there a more idiomatic way to achieve the same thing?


Solution

  • If "doStuff" is a slot then you can use QMetaObject::invokeMethod:

    QMetaObject::invokeMethod(&worker, "doStuff", Qt::QueuedConnection, Q_ARG(int, 5));