qt4 定时器
方法1----跟vc中差不多
先添加几个私有成员保存系统随机分配的定时器编号;添加定时器slot,某个定时器超时时系统自动去执行这个函数。
- private:
- int id1,id2,id3;
- private slots:
- void timerEvent(QTimerEvent *);
在需要的时候启动定时器
- id1 = startTimer(1000); //其返回值为timerId
- id2 = startTimer(5000);
- id3 = startTimer(10000);
实现定时器slot
- void MainWindow::timerEvent(QTimerEvent *t) //定时器事件
- {
- if(t->timerId()==id1){
- QMessageBox::warning(this,"title",tr("timer%1").arg(t->timerId()));
- //killTimer(t->timerId());
- }
- else if(t->timerId()==id2){
- QMessageBox::warning(this,"title",tr("timer%1").arg(t->timerId()));
- //killTimer(t->timerId());
- }
- else {
- QMessageBox::warning(this,"title",tr("timer%1").arg(t->timerId()));
- //killTimer(t->timerId());
- }
- }
在需要的时候
- killTimer(id1);
- killTimer(id2);
- killTimer(id3);
方法2.
先添加定时器指针及slot
- private:
- QTimer *timer;
- private slots:
- void timerUpDate();
然后在需要时候创建定时器并连接signal与slot
- timer = new QTimer(this);
- connect(timer,SIGNAL(timeout()),this,SLOT(timerUpDate()));
- timer->start(1000);
实现slot
- void MainWindow::timerUpDate()
- {
- QDateTime time = QDateTime::currentDateTime();
- //获取系统现在的时间
- QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd");
- //设置系统时间显示格式
- ui->label->setText(str);
- //在标签上显示时间
- }
在需要的时候杀掉
- timer->stop();
http://www.yafeilinux.com/?p=51