QT : 多线程使用定时器

方法一:

run()函数中初始化和start timer。

void MyThread::run()
{
    timer = new QTimer();
    timer->setInterval(100); //这里要用setInterval来设置间隔
    connect(timer,SIGNAL(timeout()),this,SLOT(timerOut()));
    timer->start();
    this->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();
}