环境:VS2017+Qt5.10.0
目标:设计钟表如下图所示:
代码:
MyLCDNumber.hpp
#pragma once
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QLCDNumber>
class MyLCDNumber : public QMainWindow
{
Q_OBJECT
public:
MyLCDNumber(QWidget *parent = Q_NULLPTR);
public slots:
void onTimeOut();
private:
QLCDNumber* plcd;
};
MyLCDNumber.cpp
#include "MyLCDNumber.hpp"
#include <QtWidgets/QLCDNumber>
#include <QtCore/QTimer>
#include <QtCore/QDateTime>
#include <QtWidgets/QVBoxLayout>
MyLCDNumber::MyLCDNumber(QWidget *parent)
: QMainWindow(parent)
{
this->setWindowTitle("clock");
this->setFixedSize(400, 100);
plcd = new QLCDNumber(this);
plcd->setFixedSize(400, 100);
plcd->setDigitCount(23); //设置晶体管控件QLCDNumber能显示的位数对齐,靠右
plcd->setMode(QLCDNumber::Dec); //设置显示的模式为十进制
plcd->setStyleSheet("border: 1px solid green; color: green; background: silver; background-color: black");
plcd->setSegmentStyle(QLCDNumber::Flat); //设置显示方式
QTimer* timer = new QTimer(this);
timer->setInterval(1000); //设置定时器每个多少毫秒发送一个timeout()信号
timer->start(); //启动定时器
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(plcd);
this->setLayout(layout);
connect(timer, SIGNAL(timeout()), this, SLOT(onTimeOut()));
}
void MyLCDNumber::onTimeOut()
{
QDateTime dataTime = QDateTime::currentDateTime();
plcd->display(dataTime.toString("yyyy-MM-dd HH:mm:ss.zzz")); //显示的内容
}
注意问题:
1) connect(timer, SIGNAL(QtTimer::timeout()), this, SLOT(onTimeOut())); 信号槽无效
2) plcd->setDigitCount(23); 如果QLCDNumber宽度太小,而setDigitCount设置的数字较大,则无法显示内容
3) plcd->setDigitCount(23) 和 plcd->display(dataTime.toString("yyyy-MM-dd HH:mm:ss.zzz")); 最好保持位数相同,默认右对齐
4) plcd 显示的字体大小 = plcd 宽度 / setDigitCount() 中设置的显示位数,所以要注意设置plcd控件的宽度
参考链接:
https://blog.csdn.net/liang19890820/article/details/50917205