QTimer與QTime實現(xiàn)電子時鐘
更新時間:2020年05月30日 08:58:09 作者:Saqino
這篇文章主要為大家詳細介紹了QTimer與QTime實現(xiàn)電子時鐘,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了QTimer與QTime實現(xiàn)電子時鐘的具體代碼,供大家參考,具體內(nèi)容如下
使用QLCDNumber控件進行顯示
QLCDNumber控件默認只顯示5個字符,可以使用setDigitCount(int size)進行設(shè)置顯示個數(shù)
使用Display(QString str) 設(shè)置顯示內(nèi)容
該函數(shù)擁有多個重載,字符 整型 浮點型都可以作為參數(shù)
效果圖:

代碼:頭文件
#include <QLCDNumber>
class NumClock : public QLCDNumber
{
Q_OBJECT
public:
explicit NumClock(QWidget *parent = nullptr);
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *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::NumClock(QWidget *parent) : QLCDNumber(parent)
{
timer = new QTimer(this);
timer->setTimerType(Qt::PreciseTimer); // 設(shè)置精度為較高精度,差距在毫秒內(nèi)
timer->start(1000);
connect(timer, SIGNAL(timeout()), this, SLOT(updateTime()),Qt::QueuedConnection);
setWindowFlag(Qt::FramelessWindowHint); //沒有面板邊框標題欄的窗體
setWindowOpacity(0.5); //設(shè)置窗口的透明度
showColon = true;
this->setDigitCount(8);
resize(150, 100);
updateTime();
setAttribute(Qt::WA_DeleteOnClose);
}
void NumClock::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton){
mouseOfPonit = event->globalPos() - this->pos();
event->accept();
}else{
close();
}
}
void NumClock::mouseMoveEvent(QMouseEvent *event)
{
if(event->buttons() & Qt::LeftButton){
move(event->globalPos() - mouseOfPonit);
event->accept();
}
}
void NumClock::updateTime()
{
QString timeStr = QTime::currentTime().toString("hh:mm:ss");
if(showColon){
timeStr = timeStr.replace(QString(":"), QString(" "));
qDebug() << timeStr;
showColon = false;
}else{
timeStr = timeStr.replace(QString(" "), QString(":"));
showColon = true;
qDebug() << timeStr;
}
display(timeStr);
}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

