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 :)
-
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. -
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
{
public:
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:
work()
{
...
}private:
QTimer* _timer;
};...
QThread* thread = new QThread;
Worker* worker = new Worker;
worker->moveToThread(thread);
connect(..., ..., worker, SLOT(startTimer()));
connect(..., ..., worker, SLOT(stopTimer()));thread->start();
@
Brain to terminal. Not tested. Exemplary. -