I am trying to start a QTimer in a specific thread. However, the timer does not seem to execute and nothing is printing out. Is it something to do with the timer, the slot or the thread?
main.cpp
#include "MyThread.h"
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
MyThread t;
t.start();
while(1);
}
MyThread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QTimer>
#include <QThread>
#include <iostream>
class MyThread : public QThread {
Q_OBJECT
public:
MyThread();
public slots:
void doIt();
protected:
void run();
};
#endif /* MYTHREAD_H */
MyThread.cpp
#include "MyThread.h"
using namespace std;
MyThread::MyThread() {
moveToThread(this);
}
void MyThread::run() {
QTimer* timer = new QTimer(this);
timer->setInterval(1);
timer->connect(timer, SIGNAL(timeout()), this, SLOT(doIt()));
timer->start();
}
void MyThread::doIt(){
cout << "it works";
}
You can use the emit signal and start the timer inside the emitted slot function
main.cpp
MyThread.h
MyThread.cpp
You need an event loop to have timers. Here's how I solved the same problem with my code:
Here's the relevant piece of the documentation that none of the other posters mentioned:
A
QTimer
only works in a thread that has an event loop.http://qt-project.org/doc/qt-4.8/QTimer.html
As I commented (further information in the link) you are doing it wrong :
doIt()
). They should be separated.QThread
in your case. Worse, you are overriding therun
method without any consideration of what it was doing.This portion of code should be enough
Now (Qt version >= 4.7) by default
QThread
starts a event loop in hisrun()
method. In order to run inside a thread, you just need to move the object. Read the doc...I have created an example that calls the timer within a lambda function: