【QT】定时器

新建项目

添加文件

改头文件

提升

1 第一种方式

(1)利用事件 void timerEvent ( QTimerEvent * ev)
(2)启动定时器 startTimer( 1000) 毫秒单位
(3)timerEvent 的返回值是定时器的唯一标示 可以和ev->timerid 做比较

需求:设置两个定时器,时间不一样。

(1)首先是重写timerEvent函数

这里加上UI的label控件

 重写

// 定时器事件
void Widget::timerEvent(QTimerEvent *event) {
    if (event->timerId() == this->m_Id1) {
        static int num = 1;
        ui->label->setText(QString::number(num++));
    } else if (event->timerId() == this->m_Id2){
        static int num2 = 1;
        ui->label_2->setText(QString::number(num2++));
    }

}

(2)因为是两个定时器,在类中加入成员属性,各表示两个定时器的返回值

(3)启动两个定时器

// 启动定时器
this->m_Id1 = startTimer(1000);     // 毫秒级

this->m_Id2 = startTimer(2000);

(4)效果

代码

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTimer>

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

    int m_Id1;
    int m_Id2;

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

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

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

    //  启动定时器
//    startTimer(1000);           //  单位是ms
    this->m_Id1 = startTimer(1000);

    this->m_Id2 = startTimer(2000);
}

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


// 定时器事件
void Widget::timerEvent(QTimerEvent *event) {
    //  判断定时器
    if (event->timerId() == this->m_Id1) {
        static int num = 1;
        ui->label->setText(QString::number(num++));
    } else if (event->timerId() == this->m_Id2){
        static int num2 = 1;
        ui->label_2->setText(QString::number(num2++));
    }

}

2 第二种方式

添加一个label

定时器类

// 定时器类
QTimer* timer = new QTimer(this);
timer->start(500);       // 单位是毫秒
// 监听定时器对象的信号
connect(timer, &QTimer::timeout, this, [=](){
    static int num3 = 1;
    ui->label_3->setText(QString::number(num3++));
});

效果

扩充,点击暂停按钮,定时器暂停

添加QPushbutton按钮,使用connect做连接

    // 监听暂停
    connect(ui->pushButton, &QPushButton::clicked, this, [=]() {
        timer->stop();
    });

    // 监听开始
    connect(ui->push, &QPushButton::clicked, this, [=]() {
        timer->start();
    });

效果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值