方法一视频教程生成widget基类对象添加两个txtlabel#ifndefWIDGET_H#defineWIDGET_H#includeQWidgetQT_BEGIN_NAMESPACEn...
方法一
视频教程
生成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;
}
效果图

到此这篇关于Qt实现定时器的两种方法分享的文章就介绍到这了,更多相关Qt定时器内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!










