我试图在工作线程事件循环中启动计时器,但收到此错误:QObject::startTimer: Timers can only be used with threads started with QThread
这有什么问题吗?
#include <QObject>
#include <QThread>
#include <QTimer>
class A : public QObject
{
Q_OBJECT
public:
A();
private:
QThread m_workerThread;
QTimer m_myTimer;
};
A::A()
{
this->moveToThread(&m_workerThread);
m_myTimer.moveToThread(&m_workerThread);
m_workerThread.start();
m_myTimer.start(1000);
}
在任何地方初始化计时器,但在线程启动时立即启动它(将其附加到QThread::开始信号):
class A : public QObject
{
Q_OBJECT
public:
A();
private slots:
void started();
void timeout();
private:
QThread m_workerThread;
QTimer m_myTimer;
};
A::A()
{
moveToThread(&m_workerThread);
connect(&m_workerThread, SIGNAL(started()), this, SLOT(started()));
connect(&m_myTimer, SIGNAL(timeout()), this, SLOT(timeout()));
m_myTimer.setInterval(1000);
m_myTimer.moveToThread(&m_workerThread);
m_workerThread.start();
}
void A::started()
{
timer.start();
}
void A::timeout()
{
// timer handler
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)