Qt 之 数字钟

本例展示了 QTimer 的使用,如何定时更新一个窗口部件 DigitalClock

1  QLCDNumber 类

QLCDNumber 是一种可将数字显示为类似 LCD 形式的窗口部件,它同 QLabel 一样,都继承自 QFrame,而 QFrame 继承自 QWidget

头文件 digitalclock.h

 #include <QLCDNumber>

 class DigitalClock : public QLCDNumber
{
Q_OBJECT public:
DigitalClock(QWidget *parent = );
private slots:
void showTime();
};

DigitalClock 继承自 QLCDNumber 类,对于需要信号和槽的类,#5 处的 Q_OBJECT 宏是必需的,#8 声明构造函数,#10~11 声明槽函数 showTime()

1.1  构造函数

 DigitalClock::DigitalClock(QWidget *parent)
: QLCDNumber(parent)
{
setSegmentStyle(QLCDNumber::Filled); showTime(); setWindowTitle("Digital Clock");
resize(, );
}

1.2  槽函数

#3 获取到当前时间后,#4 将其转换为 “hh:mm” 格式,#5 显示出时间。

 void DigitalClock::showTime()
{
QTime time = QTime::currentTime();
QString text = time.toString("hh:mm");
display(text);
}

  此时,程序可以显示数字时钟,但不是实时,只在第一次运行时获取当前的时间并显示出来。为了实时显示,则需要下面的 QTimer 类。

2  QTimer 类

QTimer 类继承自 QObject,可用来实时的更新时间。构造函数如下:#6 新建一个定时器,#7 利用 connect() 函数,连接信号 timeout() 和 槽函数 showTime(),#8 开启定时器,并设置时间间隔为 1000 ms

 DigitalClock::DigitalClock(QWidget *parent)
: QLCDNumber(parent)
{
setSegmentStyle(QLCDNumber::Filled); QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(showTime()));
timer->start(); showTime(); setWindowTitle("Digital Clock");
resize(, );
}

最终的 showTime() 如下: #5 和 #6 通过取余运算,使得时钟和分钟之间的分号,每隔一秒就消失,从而实现闪烁功能

 void DigitalClock::showTime()
{
QTime time = QTime::currentTime();
QString text = time.toString("hh:mm");
if((time.second() % ) == )
text[] = ' ';
display(text);
}

界面如下:

  aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAUoAAACXCAIAAAD8nIUXAAASfkl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C0qIdFJwJs3Ad6iEhKdBLx5E+AtKiHRScCbNwHeohISnQS8eRPgLSoh0UnAmzcB3qISEp0EvHkT4C0qIdFJwJs3Ad6iEhKdBLx5E+AtKiHRScCbNwHeohISnQS8eRPgLSoh0UnAmzcB3ixFWVSioqUW4A14A94VK1pqIXFTgDdvArwFVbTUQuKmAG/eBHgLqmiphcRNAd68CfAWVNFSC4mbArx5E+AtqKKlFhI3BXjzJsBbUEVLLSRuCvDmTYC3oIqWWkjcFODNmwBvQRUttZC4KcCbNwHeLEU1zCpR0VIL8Aa8AW9shUQnAW/eBHiLSkh0EvDmTYC3qIREJwFv3kQQRE1NjfDxLm6ToCwh0ckSbVKMeEejUbVaTdvN4vBWq9VECaTX64vYJChXxcXNIlTiJsSJd5Qh8iLwVqvVN2/ePHXqFC35u9Ho6Cht5Gj1WSAqIm4mjYyMoBK3ePGO0kVeKN6lY5slcuT6LBAVGjetSsR2ieIWNd7RnMgLwrvUbDNFjmKfBaKC4s5VSdkuRdxixzuaGXn+eJeHbdrIEe2zQJR/3FkqA9u8xw14R6OUyPPEu5xs50aObp8FojzjpqpsbPMbN+CdEBl5PniXn+2syJHus0CUT9wplZltHuMGvNNSq9WceFeKbWrkqPdZIOKMm1RF2OYrbsA7Q5x4V5DtVOQ2m61sDcFbnCe2gmzzEjfgXYA0glGlOyEKVTrktIq+BcC7AMXj8UpvAVQ+YRA34A0CYSvAGwTCVoA3CIStAG8QCFsB3iAQtgK8QSBsxSfeIBBIaOIH7/L/rh8EAuUjHvAGg8GoGPAGg7E14A0GY2vAGwzG1oA3GIytAW8wGFtz4A0Gg5E2I94gEAgD0eANAoHwE+ANAmErwBsEwlb/D3QNtp+dY3WbAAAAAElFTkSuQmCC" alt="" width="323" height="148" />

参考资料

Qt 助手,Qt 5.8 | Qt Widgets | Digital Clock Example

上一篇:数据网格和树-EasyUI Datagrid 数据网格、EasyUI Propertygrid 属性网格、EasyUI Tree 树、EasyUI Treegrid 树形网格


下一篇:(数组) leetcode 66. Plus One