DigitalClock.h
#ifndef DIGITALCLOCK_H
#define DIGITALCLOCK_H
#include <QLCDNumber>
class DigitalClock : public QLCDNumber
{
Q_OBJECT
public:
DigitalClock(QWidget *parent = nullptr);
private slots:
void showTime();
};
#endif // WIDGET_H
DigitalClock.cpp
#include "DigitalClock.h"
#include <QTimer>
#include <QTime>
DigitalClock::DigitalClock(QWidget *parent)
: QLCDNumber(parent)
{
this->setSegmentStyle(Filled);//设置LCD
QTimer *timer = new QTimer(this);//设置一个定时器
connect(timer, &QTimer::timeout, this, &DigitalClock::showTime);//出发时,调用槽函数showTime
timer->start(1000);//每个一秒定时器出发一次
setWindowTitle(tr("Digital Clock"));
resize(900, 240);
}
void DigitalClock::showTime()
{
QTime time = QTime::currentTime();//获取当前时间存放到QTime变量中
QString text = time.toString("hh:mm:ss");//按照格式把当前时间转为字符串
if ((time.second() % 2) == 0)
text[5] = ' ';//每偶数秒,把“:”变成空白
this->setDigitCount(8);//默认显示5位需要设置一下
this->display(text);
}
main.cpp
#include "DigitalClock.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
DigitalClock w;
w.show();
return a.exec();
}