方法一:
run()函數中初始化和start timer。
void MyThread::run()
{
timer = new QTimer();
connect(timer,SIGNAL(timeout()),this,SLOT(timerOut()));
timer->start(1000);
exec();
}
void MyThread::timerOut()
{
qDebug()<<"Current Thread ID:"<<QThread::currentThreadId();
}
方法二:
run()函數中初始化timer,其他函數start timer,定時器採用信號與槽採用Qt::DirectConnection連接,這樣不會跳轉到其他線程。
void MyThread::run()
{
timer = new QTimer();
connect(timer,SIGNAL(timeout()),this,SLOT(timerOut()),Qt::DirectConnection);
startTimer();
exec();
}
void MyThread::startTimer(){
qDebug()<<"Current Thread ID:"<<QThread::currentThreadId();
timer->start(1000);
}
void MyThread::timerOut()
{
qDebug()<<"Current Thread ID:"<<QThread::currentThreadId();
}