我正在尝试在特定线程中启动 QTimer.但是,计时器似乎没有执行,也没有打印出任何内容.是跟定时器、槽还是线程有关?
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
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";
}
正如我所评论的(链接中的更多信息),您做错了:
As I commented (further information in the link) you are doing it wrong :
doIt()
)混合在一起.他们应该分开.QThread
进行子类化.更糟糕的是,您覆盖了 run
方法,而没有考虑它在做什么.doIt()
). They should be separated.QThread
in your case. Worse, you are overriding the run
method without any consideration of what it was doing.这部分代码应该够了
QThread* somethread = new QThread(this);
QTimer* timer = new QTimer(0); //parent must be null
timer->setInterval(1);
timer->moveToThread(somethread);
//connect what you want
somethread->start();
现在(Qt 版本 >= 4.7)默认 QThread
在他的 run()
方法中启动一个事件循环.为了在线程内运行,您只需要移动对象.阅读文档...
Now (Qt version >= 4.7) by default QThread
starts a event loop in his run()
method. In order to run inside a thread, you just need to move the object. Read the doc...
这篇关于在 QThread 中启动 QTimer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!