1.源码文件
QTime类的实现是在qdatetime.h文件中
可以参考https://code.woboq.org/qt5/qtbase/src/corelib/time/qdatetime.cpp.html
该链接查看源码
2.类中一些函数方法的实现
1. QTime QTime::currentTime()
方法描述
代码实现
window平台:
unix平台:
2. QString QTime::toString(const QString &format) const
3.效果实现
4.实现机制
利用qt自带timer机制,每隔1000ms刷新一次。
5.代码展示
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QString>
#include <QTime>
#include <QDebug>
#include <QLabel>
#include <QTimer>
#include<iostream>
#include<QDebug>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
Widget(QString format_);
~Widget();
QString GetTime(const QString& format);
void timerEvent(QTimerEvent *event);
private:
Ui::Widget *ui;
QLabel* timeLabel;
QTimer timer;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include "QPainter"
#include <QSize>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
startTimer(1000);
timeLabel = new QLabel();
timeLabel->setStyleSheet("QLabel{border:2px solid rgb(200, 200, 200);}");
timeLabel->setGeometry(0,0,200,40);
timeLabel->setAlignment(Qt::AlignCenter);
timeLabel->setParent(this);
}
void Widget::timerEvent(QTimerEvent *event)
{
QString format("HH:mm:ss a");
static QString timeText;
timeText = GetTime(format);
qDebug()<<timeText;
timeLabel->setText(timeText);
}
Widget::~Widget()
{
delete ui;
}
QString Widget::GetTime(const QString& format)
{
QTime time = QTime::currentTime();
if (format.isEmpty()) {
return QString();
}
QString timeText = time.toString(format);
return timeText;
}