QT : 多線程使用定時器

方法一:

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();
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章