#include "widget.h"
#include "ui_widget.h"
#include <QTimer>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//启动定时器
this->id1 = startTimer(1000); //参数1 间隔 单位:毫秒
this->id2 = startTimer(2000);
//定时器第二种使用方式 推荐这种方法
QTimer * timer = new QTimer(this);
//启动定时器
timer->start(500);
connect(timer,&QTimer::timeout,[=](){
static int num4 = 1;
ui->label_4->setText(QString::number(num4++));
});
//点击暂停按钮,停止定时器
connect(ui->pushButton,&QPushButton::clicked,[=](){
timer->stop();
});
}
Widget::~Widget()
{
delete ui;
}
//重写定时器事件
void Widget::timerEvent(QTimerEvent *e)
{
if(e->timerId() == id1)
{
// label_2 每隔1s +1
static int num = 1;
ui->label_2->setText(QString::number(num++));
}
if(e->timerId() == id2)
{
// label_3 每隔2s +1
static int num2 = 1;
ui->label_3->setText(QString::number(num2++));
}
}
Qt教程:定时器
最新推荐文章于 2023-06-24 07:15:28 发布