Search code examples
qtqmlqthread

QObject::startTimer: Timers cannot be started from another thread error


i am getting QObject::startTimer: Timers cannot be started from another thread from this snippet and it's blocking my application and freezing the UI. I am kind of new to threading in QT.

   void ReportModel::myslot(){
        moveToThread(&thread);
        connect(&thread, SIGNAL(started()), this, SLOT(exportProg()));
        thread.start();
    }

in exportProg() i am making a csv file in pendrive.


Solution

  • Given that ReportModel is likely a class used from the GUI thread, this won't work and is a bad idea. this->moveToThread(...) is usually a bad code smell unless you know exactly what you're doing.

    Why are you moving the model to a thread in a slot? Shouldn't it be in a thread from the very beginning? Why are you connecting slots to the started signal? The idiom for job submittal to the current object thread's event loop can be QTimer::singleShot(0, ...) or QMetaObject::invoke, and that works without any dependency on a thread starting at that very moment. Most likely, exportProg should be a threadsafe method that can be submitted for asynchronous execution via QtConcurrent::run.