秒表

匿名 (未验证) 提交于 2019-12-02 23:32:01

1、UI设计:

2、代码:

Qtime、Qtimer类

需求:每隔1ms,更新显示,怎么通知计时周期到:

QTimer类帮助文档:

1       QTimer *timer = new QTimer(this); 2       connect(timer, SIGNAL(timeout()), this, SLOT(update())); 3       timer->start(1000);  //1s

怎么获取时间数据:QTime帮助文档:

1 QTime 定义一个对象,它可以记录时间,并且可以人为指定时间,还有addMSecs方法可以实现增加指定毫秒,从而达到计数。

 1 Example:  2   3   QTime n(14, 0, 0);                // n == 14:00:00  4   QTime t;  5   t = n.addSecs(70);                // t == 14:01:10  6   t = n.addSecs(-70);               // t == 13:58:50  7   t = n.addSecs(10 * 60 * 60 + 5);  // t == 00:00:05  8   t = n.addSecs(-15 * 60 * 60);     // t == 23:00:00  9  10 See also addMSecs(), secsTo(), and QDateTime::addSecs().

通过toString方法可以获取一个QString类型的时间字符串:

1 QString QTime::toString(const QString &format) const 2  3  4 Format ---> Result 5 hh:mm:ss.zzz              14:13:09.042 6 h:m:s ap                  2:13:9 pm 7 H:m:s a                   14:13:9 pm

怎么显示到QLCDNumber控件:QLCDNumber帮助文档:

1 [slot] void QLCDNumber::display(const QString &s) 2 Displays the number represented by the string s.

这里的display方法是一个槽函数,这就是说明,槽函数可以像普通函数一样被调用,而不一定非要绑定信号才能调用。

 1 #ifndef MAINWINDOW_H  2 #define MAINWINDOW_H  3   4 #include <QMainWindow>  5 #include <QTime>  6 #include <QTimer>  7   8 namespace Ui {  9 class MainWindow; 10 } 11  12 class MainWindow : public QMainWindow 13 { 14     Q_OBJECT 15  16 public: 17     explicit MainWindow(QWidget *parent = nullptr); 18     ~MainWindow(); 19  20  21 private slots: 22     void update_my_timer(); 23  24     void on_btn_begin_clicked(); 25  26 private: 27     QTime count_time;       //计数,用于更新定时器 28     QTimer* p_timer;        //定时器 29     Ui::MainWindow *ui; 30 }; 31  32 #endif // MAINWINDOW_H
 1 #include "mainwindow.h"  2 #include "ui_mainwindow.h"  3 #include <QDebug>  4   5 MainWindow::MainWindow(QWidget *parent) :  6     QMainWindow(parent),  7     ui(new Ui::MainWindow)  8 {  9     ui->setupUi(this); 10     this->p_timer = new QTimer(); 11     connect(this->p_timer, SIGNAL(timeout()), this, SLOT(update_my_timer())); //绑定定时器和槽函数 12  13 } 14  15 MainWindow::~MainWindow() 16 { 17     delete ui; 18 } 19  20  21 //计时周期到响应的槽函数 22 void MainWindow::update_my_timer(){ 23     //1、更新当前计数 24     this->count_time = this->count_time.addMSecs(1); //增加1ms 25     //2、控件显式更新 26     QString timev = this->count_time.toString("hh:mm:ss.zzz"); 27     qDebug()<<timev; 28     this->ui->lcdNumber->display(timev); 29  30 } 31  32 //点击开始按钮之后触发计时器开始计时 33 void MainWindow::on_btn_begin_clicked() 34 { 35     this->p_timer->start(1);  //启动1ms周期的定时器开始计时 36     //0、清空计数 37     this->count_time.setHMS(0,0,0,0); 38 }

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!