复现就是有手就行。
效果如下所示:
界面是通过QtDesigner拖拽出来滴。
接下来是实现的代码,头文件:
#pragma once
#include <QWidget>
#include <qtimer.h>
#include "ui_SimpleTimer.h"
class SimpleTimer : public QWidget
{
Q_OBJECT
public:
SimpleTimer(QWidget *parent = Q_NULLPTR);
~SimpleTimer();
private:
void Init();
void InitConnect();
private slots:
void SlotInitButton(bool _checked);
void SlotBeginButton(bool _checked);
void SlotEndButton(bool _checked);
private:
Ui::SimpleTimer ui;
QTimer* run_timer_;
double run_time_s_;
};
源文件:
#include "SimpleTimer.h"
#include <qdatetime.h>
SimpleTimer::SimpleTimer(QWidget *parent)
: QWidget(parent)
, run_time_s_(0)
{
ui.setupUi(this);
Init();
InitConnect();
}
SimpleTimer::~SimpleTimer()
{
}
void SimpleTimer::Init()
{
run_timer_ = new QTimer(this);
connect(run_timer_, &QTimer::timeout, [=]() {
run_time_s_ += 0.1;
// 保留小数点后三位显示
QString str_run_time_s = QString::number(run_time_s_, 'f', 3);
ui.run_time_s->display(str_run_time_s);
int run_time = run_time_s_;
int h = run_time / (60 * 60);
int m = (run_time - (h * 60 * 60)) / 60;
int s = (run_time - (h * 60 * 60)) - m * 60;
// 整数前面补0
QString str_run_time = QString("%1").arg(h, 2, 10, QLatin1Char('0')) + ":"
+ QString("%1").arg(m, 2, 10, QLatin1Char('0')) + ":"
+ QString("%1").arg(s, 2, 10, QLatin1Char('0'));
ui.run_time->display(str_run_time);
});
// 定时器
QTimer* current_time = new QTimer(this);
current_time->start(0);
// 使用定时器信号槽,尽快更新时间的显示
connect(current_time, &QTimer::timeout, [=]() {
QDateTime data_time = QDateTime::currentDateTime();
// 显示时间,格式为:年-月-日 时:分:秒
QString str_current_time = data_time.toString("yyyy-MM-dd hh:mm:ss");
// 时间显示格式可自由设定
ui.local_time->setDigitCount(19);
ui.local_time->setFixedSize(300, 60);
ui.local_time->setSegmentStyle(QLCDNumber::Flat);
ui.local_time->display(str_current_time);
});
ui.run_time->setDigitCount(9);
ui.run_time->setFixedSize(150, 60);
ui.run_time->setSegmentStyle(QLCDNumber::Flat);
ui.run_time->display("00:00:00");
// 仿真运行时间
ui.run_time_s->setDigitCount(9);
ui.run_time_s->setFixedSize(150, 60);
ui.run_time_s->setSegmentStyle(QLCDNumber::Flat);
ui.run_time_s->display("00000.000");
}
void SimpleTimer::InitConnect()
{
connect(ui.init_tool_button, SIGNAL(clicked(bool)), this, SLOT(SlotInitButton(bool)));
connect(ui.begin_tool_button, SIGNAL(clicked(bool)), this, SLOT(SlotBeginButton(bool)));
connect(ui.stop_tool_button, SIGNAL(clicked(bool)), this, SLOT(SlotEndButton(bool)));
}
void SimpleTimer::SlotInitButton(bool _checked)
{
run_time_s_ = 0;
ui.run_time->display("00:00:00");
ui.run_time_s->display("00000.00");
}
void SimpleTimer::SlotBeginButton(bool _checked)
{
if (run_timer_->isActive() == false)
run_timer_->start(100);
}
void SimpleTimer::SlotEndButton(bool _checked)
{
if (run_timer_->isActive() == true)
run_timer_->stop();
}
主函数啥也没写,就show了一下:
#include"SimpleTimer.h"
#include <QtWidgets/QApplication>
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
SimpleTimer simple_timer;
simple_timer.show();
return a.exec();
}