qt 定時器在子線程中運行

頭文件中

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

 

 

參考https://www.cnblogs.com/hellovenus/p/qt_thread_timer.html

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