Intellectual and witty
Qt 定时器可以用于实现定时任务,例如在指定的时间间隔内执行某些操作或函数。Qt 提供了 QTimer 类来实现定时器功能,可以使用它来定时触发事件,并在指定的时间间隔内执行特定的操作。
头文件:#include<QTimerEvent>
:#include<QTimer>
Widget.h代码:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include<QTimerEvent>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void timerEvent(QTimerEvent *);
private:
Ui::Widget *ui;
int idt1;
int idt2;
};
#endif // WIDGET_H
Widget.cpp代码:
创建定时器有两种方式:
1.使用定时器返回的定时器id,调用不同的定时器实现定时
2.使用定时器对象,通过信号槽启动和暂停定时
#include "widget.h"
#include "ui_widget.h"
#include<QString>
#include<QTimer>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
//使用定时器
//方式1
idt1 = startTimer(1000);//启动定时器哦,返回定时器id
idt2 = startTimer(2000);
//方式2
//创建定时器对象
QTimer *timer = new QTimer(this);
//timer->start(100);//启动定时器,每隔100ms发送一次信号
ui->label_4->setText("0");
connect(timer,&QTimer::timeout,[=](){
static int num_1 = 1;
ui->label_4->setText(QString::number(num_1++));
});
//需求按钮控制定时器开始与暂停
connect(ui->pushButton,&QPushButton::clicked,[=](){
timer->start(100);
});
connect(ui->pushButton_2,&QPushButton::clicked,[=](){
timer->stop();
});
}
void Widget::timerEvent(QTimerEvent *ev){
//判断定时器id
if(ev->timerId() == idt1){
static int num1 = 0;
ui->label_2->setText(QString::number(num1++));
}
if(ev->timerId() == idt2){
static int num2 = 0;
ui->label_3->setText(QString::number(num2++));
}
}
Widget::~Widget()
{
delete ui;
}
效果: