Qt实现定时器的两种方法分享
天人合一peng 人气:0方法一
生成widget基类对象
添加两个txtlabel
#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* timer); int timeId1; int timeId2; private: Ui::Widget *ui; }; #endif // WIDGET_H
#include "widget.h" #include "ui_widget.h" #include <QDebug> //#include <QTimerEvent> //#include <QTimer> Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); timeId1 = startTimer(1000); timeId2 =startTimer(2000); } void Widget::timerEvent(QTimerEvent* timer) { if(timer->timerId() == timeId1) { static int num = 1; ui->label_3->setText(QString::number(num++)); } else if(timer->timerId() == timeId2) { static int num = 1; ui->label_4->setText(QString::number(num++)); } } Widget::~Widget() { delete ui; }
效果图
方法二
#include "widget.h" #include "ui_widget.h" #include <QDebug> #include <QTimer> Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); timeId1 = startTimer(1000); timeId2 =startTimer(2000); QTimer* timer = new QTimer(this); timer->start(500); connect(timer, &QTimer::timeout,[=]() { static int num = 1; ui->label_5->setText(QString::number(num++)); }); // 定时器停止 // connect(ui->pushbtn_stop, &QPushButton::clicked, timer,&QTimer::stop); connect(ui->pushbtn_stop, &QPushButton::clicked, [=](){ timer->stop(); }); } void Widget::timerEvent(QTimerEvent* timer) { if(timer->timerId() == timeId1) { static int num = 1; ui->label_3->setText(QString::number(num++)); } else if(timer->timerId() == timeId2) { static int num = 1; ui->label_4->setText(QString::number(num++)); } } Widget::~Widget() { delete ui; }
效果图
加载全部内容