Qt实现定时器的两种方法分享
作者:天人合一peng
这篇文章主要为大家详细介绍了Qt中实现定时器的两种不同方法,文中的示例代码讲解详细,对我们了解Qt有一定的帮助,感兴趣的可以跟随小编一起学习一下
方法一
生成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定时器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
