Qt實現(xiàn)定時器的兩種方法分享
更新時間:2022年11月28日 09:27:20 作者:天人合一peng
這篇文章主要為大家詳細介紹了Qt中實現(xiàn)定時器的兩種不同方法,文中的示例代碼講解詳細,對我們了解Qt有一定的幫助,感興趣的可以跟隨小編一起學(xué)習(xí)一下
方法一
生成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;
}效果圖

到此這篇關(guān)于Qt實現(xiàn)定時器的兩種方法分享的文章就介紹到這了,更多相關(guān)Qt定時器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++?LeetCode0538二叉搜索樹轉(zhuǎn)換累加樹示例
這篇文章主要為大家介紹了C++?LeetCode0538二叉搜索樹轉(zhuǎn)換累加樹示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12
C++編程中使用設(shè)計模式中的policy策略模式的實例講解
這篇文章主要介紹了C++編程中使用設(shè)計模式中的policy策略模式的實例講解,文章最后對策略模式的優(yōu)缺點有一個簡單的總結(jié),需要的朋友可以參考下2016-03-03
實例講解C++設(shè)計模式編程中State狀態(tài)模式的運用場景
這篇文章主要介紹了實例講解C++設(shè)計模式編程中State狀態(tài)模式的運用場景,文章最后的適用性部分則介紹了一些State模式善于處理的情況,需要的朋友可以參考下2016-03-03
一起來學(xué)習(xí)C++的構(gòu)造和析構(gòu)
這篇文章主要為大家詳細介紹了C++構(gòu)造和析構(gòu),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-03-03

