Qt 中Qtimer的使用

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



發佈了69 篇原創文章 · 獲贊 46 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章