Qt5.9设计一个简略的计时器 天天动态
2023-05-17 14:40:58来源:QT教程


(资料图片仅供参考)

本文主要总结一个自定义的计时器(不是定时器),该计时器每隔一秒钟刷新一次。博主封装一个函数timeCounter(),获取每一秒的时分秒数值,封装函数返回值是一个QStringList值,里面依次返回时、分、秒三个值;封装函数代码如下:

QStringList Widget::timeCounter(){/*最多计算:24天=2073600000ms,也就是576小时*/int elapsed = time->elapsed()/1000;short int hour = 0;short int minute = 0;short int second = 0;if(elapsed>=3600){/*n hour*/hour=elapsed/3600;elapsed =elapsed%3600;}else if(elapsed>=60){/*n minute*/minute=elapsed/60;second =elapsed%60;}else if(elapsed<60){/*n second*/second =elapsed;}return QStringList()<

具体的工程示例如下所述。

1.1新建一个widget工程,不要勾选ui界面。然后分别在widget.h、widget.cpp、main.cpp分别添加如下代码。

widget.h

#ifndef WIDGET_H#define WIDGET_H#include #include class Widget : public QWidget{Q_OBJECT

public:

Widget(QWidget *parent = 0);~Widget();QStringList timeCounter();private:void setupUI();QTime *time;QTimer *timer;private slots:void slot_startedTimer_clicked(bool);void slot_stopedTimer_clicked(bool);void slot_timer_timeout();};#endif // WIDGET_H

widget.cpp

#include "widget.h"#include #include #include #include #include #include #include Widget::Widget(QWidget *parent): QWidget(parent){setupUI();}Widget::~Widget(){}void Widget::setupUI(){QVBoxLayout* mainLayout = new QVBoxLayout;mainLayout->setMargin(0);mainLayout->setSpacing(0);QPushButton *startedTimer = new QPushButton(tr("计时器start"));connect(startedTimer,SIGNAL(clicked(bool)),this,SLOT(slot_startedTimer_clicked(bool)));QPushButton *stopedTimer = new QPushButton(tr("计时器stop"));connect(stopedTimer,SIGNAL(clicked(bool)),this,SLOT(slot_stopedTimer_clicked(bool)));mainLayout->addWidget(startedTimer);mainLayout->addWidget(stopedTimer);mainLayout->addStretch();this->setLayout(mainLayout);/*初始化时间*/time = new QTime();timer = new QTimer();connect(timer,SIGNAL(timeout()),this,SLOT(slot_timer_timeout()));}void Widget::slot_startedTimer_clicked(bool){qDebug()<start();timer->start(1000);}void Widget::slot_stopedTimer_clicked(bool){qDebug()<stop();}void Widget::slot_timer_timeout(){qDebug()<elapsed()/1000;short int hour = 0;short int minute = 0;short int second = 0;if(elapsed>=3600){/*n hour*/hour=elapsed/3600;elapsed =elapsed%3600;}else if(elapsed>=60){/*n minute*/minute=elapsed/60;second =elapsed%60;}else if(elapsed<60){/*n second*/second =elapsed;}return QStringList()<

main.cpp

#include "widget.h"#include int main(int argc, char *argv[]){QApplication a(argc, argv);Widget w;w.resize(960,640);w.show();return a.exec();}

1.2程序构建和运行结果如下图所示:

【领 QT开发教程 学习资料, 点击下方链接莬费领取↓↓ ,先码住不迷路~】

点击这里:

标签:

中国—中亚峰会|哈萨克斯坦总统托卡耶夫抵达西安_环球今亮点
【新视野】校园运动会/赛事活动方案新法教育SuperME互动运动系统!

精彩推荐

资讯News

  • 聚焦Policy