定时器使用的第一种方式:事件
- 重写定时器事件

代码
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
//启动定时器
//参数1 间隔(ms为单位)
timerId1 = startTimer(1000);//每隔一秒钟调用一次定时器
timerId2 = startTimer(2000);//每个两秒钟调用一次定时器
//关闭定时器
//killTimer(timerId1);
}
//重写定时器事件
void MainWindow::timerEvent(QTimerEvent *event)
{
if(event->timerId()==timerId1)
{
static int num=1;
ui->label_2->setText(QString::number(num++));
}
if(event->timerId()==timerId2)
{
static int num=1;
ui->label_3->setText(QString::number(num++));
}
}
MainWindow::~MainWindow()
{
delete ui;
}
演示

定时器使用的第二种方式:QTimer类
代码
//定时器的第二种方式
QTimer *timer = new QTimer(this);
timer->start(500);//每隔500ms调用一次
connect(timer,&QTimer::timeout,[=](){
static int num=1;
ui->label_4->setText(QString::number(num++));
});
//点击暂停按钮 实现停止定时器
connect(ui->pushButton,&QPushButton::clicked,[=](){
timer->stop();
});
演示
