Timers cannot be stopped from another thread, but how do i stop/start timer in thread?

  • I have timer inside thread that invoking function each N seconds .
    now i have in my main window button that supposed stop/start this operation.
    so i just created in my worker thread 2 public function for starting and stooping the timer inside the thread .
    but it don't work , im getting this message :
    @QObject::killTimer: timers cannot be stopped from another thread@
    and when i try to start :
    @QObject::startTimer: timers cannot be started from another thread@
    i want to keep the thread working , and only control on the timer stop/start invocation inside the thread.
    what is the right way to do it ?

  • Use signals to start/stop times, check that "wiki page":http://developer.qt.nokia.com/wiki/ThreadsEventsQObjects

    I hope this help you :)

  • Thanks but i dont see any solution in that page , i do use the timer solution they offer
    but i need to control this timer from outside the thread

  • Add a signal to your thread class, for example
    signal startTimer();
    signal stopTimer();
    And connect it on your main class/thread, emit the signals when you want to start/stop the timer.

  • Thanks , i found the answer simple using the :
    @QMetaObject::invokeMethod(object, "methodName",
    Q_ARG(type1, arg1),
    Q_ARG(type2, arg2));

  • Be aware that slots are executed in the thread a QObject* has been created or move to, which is usually not the thread that was spawned by subclassing QThread. Thus it is recommended to not subclass QThread but creating a QObject that contains all the functionality and then moving this object to an ordinary QThread.

    class Worker : public QObject
    Worker(QObject* parent = 0) : QObject(parent), _timer(new QTimer(this))
    connect(_timer, SIGNAL(timeout()), this, SLOT(work()));

    public slots:
    void startTimer() { _timer->start(); }
    void stopTimer() { _timer->stop(); }

    private slots:

    QTimer* _timer;


    QThread* thread = new QThread;

    Worker* worker = new Worker;
    connect(..., ..., worker, SLOT(startTimer()));
    connect(..., ..., worker, SLOT(stopTimer()));


    Brain to terminal. Not tested. Exemplary.

  • This is what i did , this is how i set my thread :

    @m_MyThread = new QThread();
    m_MainWorker = new MainWorker();

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.