Mingz技术博客

...

导航

qt4 定时器

方法1----跟vc中差不多
先添加几个私有成员保存系统随机分配的定时器编号;添加定时器slot,某个定时器超时时系统自动去执行这个函数。

[cpp] view plaincopy
 
  1. private:  
  2.     int  id1,id2,id3;  
  3. private slots:  
  4.     void timerEvent(QTimerEvent *);  

在需要的时候启动定时器

[cpp] view plaincopy
 
  1. id1 = startTimer(1000); //其返回值为timerId  
  2. id2 = startTimer(5000);  
  3. id3 = startTimer(10000);  

实现定时器slot

[cpp] view plaincopy
 
  1. void MainWindow::timerEvent(QTimerEvent *t) //定时器事件  
  2. {  
  3.     if(t->timerId()==id1){  
  4.             QMessageBox::warning(this,"title",tr("timer%1").arg(t->timerId()));  
  5.             //killTimer(t->timerId());  
  6.         }  
  7.     else if(t->timerId()==id2){  
  8.         QMessageBox::warning(this,"title",tr("timer%1").arg(t->timerId()));  
  9.         //killTimer(t->timerId());  
  10.     }  
  11.     else {  
  12.             QMessageBox::warning(this,"title",tr("timer%1").arg(t->timerId()));  
  13.             //killTimer(t->timerId());  
  14.     }  
  15. }  

在需要的时候

[cpp] view plaincopy
 
  1. killTimer(id1);  
  2. killTimer(id2);  
  3. killTimer(id3);  


方法2.
先添加定时器指针及slot

[cpp] view plaincopy
 
  1. private:  
  2.     QTimer *timer;  
  3. private slots:  
  4.     void timerUpDate();  

然后在需要时候创建定时器并连接signal与slot

[cpp] view plaincopy
 
  1. timer = new QTimer(this);  
  2. connect(timer,SIGNAL(timeout()),this,SLOT(timerUpDate()));  
  3. timer->start(1000);  

实现slot

[cpp] view plaincopy
 
  1. void MainWindow::timerUpDate()  
  2. {  
  3. QDateTime time = QDateTime::currentDateTime();  
  4. //获取系统现在的时间  
  5. QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd");  
  6. //设置系统时间显示格式  
  7. ui->label->setText(str);  
  8. //在标签上显示时间  
  9. }  

在需要的时候杀掉

[cpp] view plaincopy
 
  1. timer->stop();  



http://www.yafeilinux.com/?p=51

posted on 2013-07-24 16:48  Mingz2013  阅读(208)  评论(0编辑  收藏  举报