• QT学习笔记(14) 定时器类QTimer的使用


    一、

      在前面的学习笔记中,我们已经学习定时器事件http://www.cnblogs.com/blog-ccs/p/7445323.html

      现在,我们学习QTimer定时器类,比较优劣。

    二、示例代码

    widget.h

     1 #ifndef WIDGET_H
     2 #define WIDGET_H
     3 
     4 #include <QWidget>
     5 #include <QTimer>//定时器对象
     6 
     7 namespace Ui {
     8 class Widget;
     9 }
    10 
    11 class Widget : public QWidget
    12 {
    13     Q_OBJECT
    14 
    15 public:
    16     explicit Widget(QWidget *parent = 0);
    17     ~Widget();
    18 
    19 private slots:
    20     void on_pushButton_start_clicked();
    21 
    22     void on_pushButton_stop_clicked();
    23 
    24 private:
    25     Ui::Widget *ui;
    26 
    27     QTimer *myTimer;//定时器对象
    28     //一个对象对应一个定时器,如果想再有一个定时器,则可以直接再创建一个定时器对象即可
    29 };
    30 
    31 #endif // WIDGET_H

    widget.cpp

     1 #include "widget.h"
     2 #include "ui_widget.h"
     3 
     4 Widget::Widget(QWidget *parent) :
     5     QWidget(parent),
     6     ui(new Ui::Widget)
     7 {
     8     ui->setupUi(this);
     9 
    10     myTimer = new QTimer(this);
    11 
    12     //在定时器启动之后,每隔时间间隔都会触发timeout()信号
    13     connect(myTimer,&QTimer::timeout,
    14             [=]()
    15             {
    16                 static int i = 0;
    17                 i++;
    18                 ui->lcdNumber->display(i);
    19             }
    20             );
    21 
    22 }
    23 
    24 Widget::~Widget()
    25 {
    26     delete ui;
    27 }
    28 
    29 void Widget::on_pushButton_start_clicked()
    30 {
    31     //启动定时器
    32     //时间间隔为100ms
    33     //每隔100ms,定时器内部myTimer自动触发timeout()信号
    34     if(myTimer->isActive() == false)
    35     {
    36         myTimer->start(100);
    37     }
    38 }
    39 
    40 void Widget::on_pushButton_stop_clicked()
    41 {
    42     //定时器停止
    43     if(myTimer->isActive() == true)
    44     {
    45         myTimer->stop();
    46     }
    47 }

    widget.ui界面

  • 相关阅读:
    日程管理APP测试用例
    日程管理APP的测试计划和测试矩阵
    Bug report——仿网易新闻APP
    NABCD模拟实验
    5w1h

    小组作业
    code review
    Mutual review
    阅读思考
  • 原文地址:https://www.cnblogs.com/blog-ccs/p/7459424.html
Copyright © 2020-2023  润新知