Qt QTimerEvent 定時器事件


QTimerEvent類用來描述一個定時器事件。starttimer開啟一個定時器,傳入一個參數為超時時間,毫秒為單位。返回值是一個timerid,在timerEvent事件函數中,根據timerid來實現超時函數。

MainWindow.h

 1 #ifndef MAINWINDOW_H  2 #define MAINWINDOW_H
 3  
 4 #include <QMainWindow>
 5 #include <QTimerEvent>
 6 namespace Ui {  7 class MainWindow;  8 }  9  
10 class MainWindow : public QMainWindow 11 { 12  Q_OBJECT 13  
14 public: 15     explicit MainWindow(QWidget *parent = 0); 16     ~MainWindow(); 17 protected: 18     void timerEvent(QTimerEvent* event); 19  
20 private: 21     Ui::MainWindow *ui; 22     int id1; 23     int id2; 24     int id3; 25 }; 26  
27 #endif // MAINWINDOW_H

mainwindow.cpp

 1 #include "mainwindow.h"
 2 #include "ui_mainwindow.h"
 3 #include <QDebug>
 4 MainWindow::MainWindow(QWidget *parent) :  5  QMainWindow(parent),  6     ui(new Ui::MainWindow)  7 {  8     ui->setupUi(this);  9     id1 = startTimer(1000);//開啟一個1秒定時器,返回其ID
10     id2 = startTimer(1500); 11     id3 = startTimer(2200); 12 } 13  
14 MainWindow::~MainWindow() 15 { 16     delete ui; 17 } 18  
19 void MainWindow::timerEvent(QTimerEvent *event) 20 { 21     if(event->timerId() == id1) 22  { 23         qDebug()<<"timer1"; 24  } 25     else if(event->timerId() == id2) 26  { 27         qDebug()<<"timer2"; 28  } 29     else
30  { 31         qDebug()<<"timer3"; 32  } 33 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM