Qt实现定时器的两种方法分享

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Qt实现定时器的两种方法分享

天人合一peng   2022-11-30 我要评论

方法一

视频教程

生成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;
}

效果图

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们