1.定时器Timer类
创建一个QTimer对象,将信号timeout()与相应的槽函数相连,然后调用start()函数。接下来,每隔一段时间,定时器便会发出一次timeout()信号。
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(1000);
2.在线程中使用QTimer
void Thread::run()
{
cTimer = new QTimer();
cTimer->setInterval(1000);
connect(cTimer, &QTimer::timeout, this, &Thread::timeoutSlot);
cTimer->start();
this->exec();
}
注意:在线程中使用QTimer不能使用new QTimer(this)这样给定时器指定父对象,否则会出现错误。
必须加上exec();否则会出现 QObject::killTimer: Timers cannot be stopped from another thread错误。
3.在线程中使用QTimer 2
TestClass::TestClass(QWidget *parent)
: QWidget(parent)
{
m_pThread = new QThread(this);
m_pTimer = new QTimer();
m_pTimer->moveToThread(m_pThread);
m_pTimer->setInterval(1000);
connect(m_pThread, SIGNAL(started()), m_pTimer, SLOT(start()));
connect(m_pTimer, &QTimer::timeout, this, &ThreadTest::timeOutSlot, Qt::DirectConnection);
}