QT定時器事件的實現(xiàn)示例
定時器第一種辦法:
1.利用事件timerEvent,在幫助文檔中找到該字段:[override virtual protected] void QTimer::timerEvent(QTimerEvent *e)重寫該虛函數(shù)
//重寫定時器事件 void timerEvent(QTimerEvent *e);
2.啟動定時器startTimer(1000);
3.startTimer的返回值是定時器的唯一標(biāo)識 可以和e->timerId做比較
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); id1 = startTimer(1000); //定時器啟動,設(shè)置運行的間隔 id2 = startTimer(2000); } void MainWindow::timerEvent(QTimerEvent *e) { if(e->timerId() ==id1) { static int num = 1; //label_timer每隔1S加一 ui->label_timer->setText(QString::number(num++)); } if(e->timerId() ==id2) { static int num2 = 1; //label_timer2每隔2S加一 ui->label_timer2->setText(QString::number(num2++)); } }
這樣就實現(xiàn)了在第一個label_timer上每秒加一,在第二個label_timer2上每兩秒加一
定時器的第二種辦法:
1.利用定時器類 QTimer
2.創(chuàng)建定時器對象 QTimer * timer = new QTimer(this)
3.啟動定時器 timer->start
4.每隔設(shè)置的毫秒,發(fā)送信號timeout進(jìn)行監(jiān)聽,通過connect信號槽進(jìn)行綁定
5.暫停
#include <QTimer> //第二種辦法:定時器類 ...... //定時器第二種方式 QTimer * timer = new QTimer(this); //啟動定時器 timer->start(500); //定時器方式二到之后會發(fā)送信號 connect(timer,&QTimer::timeout,[=](){ static int num3 =1; ui->label_timer3->setText(QString::number(num3++)); }); //點擊暫停按鈕 實現(xiàn)停止定時器 connect(ui->pushButton_stopTimer,&QPushButton::clicked,[=](){ timer->stop(); });
到此這篇關(guān)于QT定時器事件的實現(xiàn)示例的文章就介紹到這了,更多相關(guān)QT定時器事件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++11中的智能指針shared_ptr、weak_ptr源碼解析
本文是基于gcc-4.9.0的源代碼進(jìn)行分析,shared_ptr和weak_ptr是C++11才加入標(biāo)準(zhǔn)的,僅對C++智能指針shared_ptr、weak_ptr源碼進(jìn)行解析,需要讀者有一定的C++基礎(chǔ)并且對智能指針有所了解2021-09-09