QT从入门到实战完整版 P32 P33

发布时间 2023-07-21 18:44:34作者: 高尔赛凡尔娟

定时器1

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 idx1;//定时器1的唯一标识
    int idx2;//定时器2的唯一标识
private:
    Ui::Widget *ui;
};
#endif // WIDGET_H

widget.cpp

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

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //启动定时器
    idx1=startTimer(1000);//参数1 间隔 单位 毫秒
    idx2=startTimer(2000);
}
void Widget::timerEvent(QTimerEvent *ev)
{
    if(ev->timerId()==idx1)
    {
        static int num=1;//label2每隔1秒+1
        ui->label_2->setText(QString::number(num++));
    }
    if(ev->timerId()==idx2)
    {
        static int num2=1;//label3每隔2秒+1
        ui->label_3->setText(QString::number(num2++));
    }
}
Widget::~Widget()
{
    delete ui;
}

定时器2

widget.cpp

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

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //启动定时器
    idx1=startTimer(1000);//参数1 间隔 单位 毫秒
    idx2=startTimer(2000);

    //定时器第二种方式
    QTimer * timer =new QTimer(this);
    //启动定时器
    timer->start(500);
    connect(timer,&QTimer::timeout,[=](){
        static int num=1;//label4每隔0.5秒+1
        ui->label_4->setText(QString::number(num++));
    });
    //点击暂停按钮 实现暂停
    connect(ui->btn,&QPushButton::clicked,[=](){
        timer->stop();
    });
}
void Widget::timerEvent(QTimerEvent *ev)
{
    if(ev->timerId()==idx1)
    {
        static int num=1;//label2每隔1秒+1
        ui->label_2->setText(QString::number(num++));
    }
    if(ev->timerId()==idx2)
    {
        static int num2=1;//label3每隔2秒+1
        ui->label_3->setText(QString::number(num2++));
    }
}
Widget::~Widget()
{
    delete ui;
}