头文件中
private:
QTimer *m_pTimer;
QThread *m_pThread;
private slots:
void timeOutSlot();
.cpp中
void ControlWidget::startThreadTime() {
qDebug() << "howard ===startThreadTime";
m_pThread = new QThread(this);
m_pTimer = new QTimer();
m_pTimer->moveToThread(m_pThread);
m_pTimer->setTimerType(Qt::PreciseTimer);
//temp_refresh_time是时间间隔
m_pTimer->setInterval(temp_refresh_time);
connect(m_pThread, SIGNAL(started()), m_pTimer, SLOT(start()));
connect(m_pTimer, SIGNAL(timeout()), this, SLOT(timeOutSlot()), Qt::DirectConnection);
m_pThread->start();
}
void ControlWidget::timeOutSlot(){
//定时时间到的回调
}
如果再次启动的话
m_pTimer->stop();
m_pTimer->destroyed();
m_pThread->wait();
m_pThread = new QThread(this);
m_pTimer = new QTimer();
m_pTimer->moveToThread(m_pThread);
m_pTimer->setTimerType(Qt::PreciseTimer);
m_pTimer->setInterval(temp_refresh_time);
connect(m_pThread, SIGNAL(started()), m_pTimer, SLOT(start()));
connect(m_pTimer, SIGNAL(timeout()), this, SLOT(timeOutSlot()), Qt::DirectConnection);
m_pThread->start();
本文详细介绍了在Qt环境下如何将线程(QThread)与定时器(QTimer)结合使用,实现定时任务的精确执行。通过创建线程和定时器对象,设置定时器类型为精确计时,并在特定时间间隔触发自定义槽函数。此外,还提供了重新启动线程和定时器的方法。
922





