本文實例為大家分享了QTimer與QTime實現電子時鐘的具體代碼,供大家參考,具體內容如下
使用QLCDNumber控件進行顯示
QLCDNumber控件默認只顯示5個字符,可以使用setDigitCount(int size)進行設置顯示個數
使用Display(QString str) 設置顯示內容
該函數擁有多個重載,字符 整型 浮點型都可以作為參數
效果圖:
代碼:頭文件
#include <QLCDNumber> class NumClock : public QLCDNumber{ Q_OBJECTpublic: 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); // 設置精度為較高精度,差距在毫秒內 timer->start(1000); connect(timer, SIGNAL(timeout()), this, SLOT(updateTime()),Qt::QueuedConnection); setWindowFlag(Qt::FramelessWindowHint); //沒有面板邊框標題欄的窗體 setWindowOpacity(0.5); //設置窗口的透明度 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);}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答
圖片精選