小编这次要给大家分享的是详解QTimer与QTime如何实现电子时钟,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。
使用QLCDNumber控件进行显示
QLCDNumber控件默认只显示5个字符,可以使用setDigitCountint size)进行设置显示个数
使用DisplayQString str) 设置显示内容
该函数拥有多个重载,字符 整型 浮点型都可以作为参数
效果图:
代码:头文件
#include <QLCDNumber>
class NumClock : public QLCDNumber
{
Q_OBJECT
public:
explicit NumClockQWidget *parent = nullptr);
void mousePressEventQMouseEvent *event);
void mouseMoveEventQMouseEvent *event);
signals:
public slots:
void updateTime);
private:
QTimer * timer;
QPoint mouseOfPonit; // 鼠标坐标跟窗口左上角坐标的偏移值
bool showColon; //是否显示:
};
cpp文件:
#include "numclock.h"
#include <QTimer>
#include <QTime>
#include <QMouseEvent>
#include <QDebug>
NumClock::NumClockQWidget *parent) : QLCDNumberparent)
{
timer = new QTimerthis);
timer->setTimerTypeQt::PreciseTimer); // 设置精度为较高精度,差距在毫秒内
timer->start1000);
connecttimer, SIGNALtimeout)), this, SLOTupdateTime)),Qt::QueuedConnection);
setWindowFlagQt::FramelessWindowHint); //没有面板边框标题栏的窗体
setWindowOpacity0.5); //设置窗口的透明度
showColon = true;
this->setDigitCount8);
resize150, 100);
updateTime);
setAttributeQt::WA_DeleteOnClose);
}
void NumClock::mousePressEventQMouseEvent *event)
{
ifevent->button) == Qt::LeftButton){
mouseOfPonit = event->globalPos) - this->pos);
event->accept);
}else{
close);
}
}
void NumClock::mouseMoveEventQMouseEvent *event)
{
ifevent->buttons) & Qt::LeftButton){
moveevent->globalPos) - mouseOfPonit);
event->accept);
}
}
void NumClock::updateTime)
{
QString timeStr = QTime::currentTime).toString"hh:mm:ss");
ifshowColon){
timeStr = timeStr.replaceQString":"), QString" "));
qDebug) << timeStr;
showColon = false;
}else{
timeStr = timeStr.replaceQString" "), QString":"));
showColon = true;
qDebug) << timeStr;
}
displaytimeStr);
}

