Qt基础 定时器的两种实现方式

本文介绍了在B站教程中,如何使用QT库通过两种方式实现定时器:一是利用事件`timerEvent`,二是采用`QTimer`类。详细讲解了如何设置UI界面元素,并演示了每种方法的代码实现,推荐使用QTimer进行实践。

根据B站《最新QT从入门到实战完整版|传智教育》学习的,BV号:BV1g4411H78N

定时器第一种实现方式

利用事件void timerEvent(QTimeEvent * ev)

启动定时器 startTime(1000) 单位是毫秒

timerEvent 的返回值是定时器的唯一标识 可以个ev->timeId作比较

第一种方式的代码部分

需要在ui界面设置label

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

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 *);

    int id1;    //定时器1的唯一标识
    int id2;    //定时器2的唯一标识

private:
    Ui::Widget *ui;
};
#endif // WIDGET_H

main.cpp是默认的

widget.cpp

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //启动定时器
    id1 = startTimer(1000);   //参数1:间隔,单位是毫秒
    id2 = startTimer(2000);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::timerEvent(QTimerEvent * ev)
{
    if(ev->timerId() == id1)
    {
        static int num = 1;

        //label_2每隔1秒+1
        ui->label_2->setText(QString::number(num++));
    }

    if(ev->timerId() == id2)
    {
        //label_3每隔2秒+1
        static int num2 = 1;
        ui->label_3->setText(QString::number(num2++));
    }

}

定时器第二种实现方式(建议使用!)

利用定时器类QTimer

创建定时器对象 QTimer * timer = new QTimer(this);

启动定时器 time->start(毫秒);

每隔一段毫秒发送信号,执行timeout,进行监听

暂停 timer->stop();

第二种方式的代码部分

需在ui界面设置tabel和pushbutton

其余部分均为默认

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QTimer>       //定时器的类
#include <QPushButton>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //定时器的第二种实现方式
    QTimer * timer = new QTimer(this);
    //启动定时器
    timer->start(500);

    connect(timer,&QTimer::timeout,[=](){
        //label_4每隔0.5秒+1
        static int num3 = 1;
        ui->label_4->setText(QString::number(num3++));
    });

    //点击停止按钮,实现停止定时器
    connect(ui->btn,&QPushButton::clicked,[=](){
        timer->stop();
    });
}

Widget::~Widget()
{
    delete ui;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值