我正在尝试在特定线程中启动 QTimer。但是,计时器似乎没有执行,也没有打印任何内容。与定时器、槽或线程有关吗?
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";
}
正如我评论的那样你做错了 https://blog.qt.io/blog/2010/06/17/youre-doing-it-wrong:
- 您将保存线程数据的对象与另一个对象混合(负责
doIt()
)。他们应该分开。
- 不需要子类化
QThread
在你的情况下。更糟糕的是,你正在超越run
方法,而不考虑它在做什么。
这部分代码应该足够了
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版本> = 5)默认情况下QThread
在其中启动一个事件循环run()
方法。为了在线程内运行,您只需移动对象即可。阅读文档... https://doc.qt.io/qt-6/qthread.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)