Qt定时器

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;
}

效果:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值