Qt之QTimer----每秒都有自己要干的事


有时候有些地方我们不得不干重复的事情,怎么办。不可能来个for,while无限循环吧,让程序一直卡在那里占cpu吧。

那我们就用定时器吧,每秒做我们想做的事,这样才是硬道理。

头文件

  1. #ifndef MAINWINDOW_H   
  2. #define MAINWINDOW_H   
  3.   
  4. #include <QMainWindow>   
  5. #include <QTimer>   
  6. #include <QDebug>   
  7. class QTime;  
  8. namespace Ui {  
  9. class MainWindow;  
  10. }  
  11.   
  12. class MainWindow : public QMainWindow  
  13. {  
  14.     Q_OBJECT  
  15.   
  16. public:  
  17.     explicit MainWindow(QWidget *parent = 0);  
  18.     ~MainWindow();  
  19.     QTimer *timer;  
  20.     int i;  
  21. private:  
  22.     Ui::MainWindow *ui;  
  23.   
  24. protected slots:  
  25.     void timerDone();  
  26.     void slotTime();  
  27. };  
  28.   
  29. #endif // MAINWINDOW_H  

源文件

  1. #include "mainwindow.h"   
  2. #include "ui_mainwindow.h"   
  3.   
  4. MainWindow::MainWindow(QWidget *parent) :  
  5.     QMainWindow(parent),  
  6.     ui(new Ui::MainWindow)  
  7. {  
  8.     ui->setupUi(this);  
  9.     i=1;  
  10.     timer = new QTimer();  
  11.     this->connect(timer,SIGNAL(timeout()),this,SLOT(timerDone()));  
  12.   
  13.     timer->start( 1000 );  //一秒钟后开始触发,然后一秒一次   
  14.   
  15.     timer->singleShot(2000,this,SLOT(slotTime()));      //2秒钟触发一次   
  16. }  
  17.   
  18. MainWindow::~MainWindow()  
  19. {  
  20.     delete ui;  
  21. }  
  22.   
  23. void MainWindow::timerDone()  
  24. {  
  25.     ui->label->setText(tr("%1").arg(i));  
  26.     i++;  
  27.     qDebug()<<"wyz========a:"<<i;  
  28. }  
  29.   
  30. void MainWindow::slotTime()  
  31. {  
  32.     i++;  
  33.     qDebug()<<"wyz========b:"<<i;  
  34. }  

效果:

D:\opt\QtOpt\qtime-build-desktop-Qt_4_7_4__qt4_7_0____\debug\qtime.exe 启动中...

Init CriticalSection spin count wyz========a: 2

wyz========b: 3

wyz========a: 4

wyz========a: 5

wyz========a: 6

wyz========a: 7

wyz========a: 8

wyz========a: 9

相关内容