代码如下:
main()函数
#include <QApplication>
#include "digitalclock.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
DigitalClock clock;
clock.show();
return app.exec();
}
main()函数没什么可以说的。
digitalclock.h#ifndef DIGITALCLOCK_H
#define DIGITALCLOCK_H
#include <QLCDNumber>
//! [0]
class DigitalClock : public QLCDNumber
{
Q_OBJECT
public:
DigitalClock(QWidget *parent = 0);
private slots:
void showTime();
};
//! [0]
#endif
第二个函数是用于显示用的
digitalclock.cpp#include <QtWidgets>
#include "digitalclock.h"
//! [0]
DigitalClock::DigitalClock(QWidget *parent)
: QLCDNumber(parent)
{
setSegmentStyle(Flat);
/*
*内置的三种显示形式::::::
* QLCDNumber::Outline
* 0
* gives raised segments filled with the background color.表示用背景颜色作为突出浮雕的颜色
*
* QLCDNumber::Filled
* 1
* gives raised segments filled with the windowText color.表示用WindowText的颜色作为突出浮雕的颜色
*
* QLCDNumber::Flat
* 2
* gives flat segments filled with the windowText color.扁平的颜色
*
*
*/
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(showTime()));
timer->start(1000);
showTime();
setWindowTitle(tr("Digital Clock"));
resize(300, 60);
}
//! [0]
//! [1]
void DigitalClock::showTime()
//! [1] //! [2]
{
QTime time = QTime::currentTime();
QString text = time.toString("hh:mm:ss");
//QLCDNumber 默认只显示5位。 可以通过 this->setNumDigits(8) 来实现你想要的功能。
qDebug()<<text<<'\n';
// if ((time.second() % 2) == 0)
// text[5] = ' ';
setDigitCount(8);
display(text);
}
//! [2]
这里主要注意的是display(text)默认的显示长度是5, 若想要显示更长的 字符串, 需要用setDigitCount()函数更改显示长度