DIY系統時間顯示

    前一篇實現了獲取系統當前時間,並動態顯示的效果;有時候拋開固有控件的軀殼,DIY一下系統時鐘效果也會讓人眼前一亮,要知道細節決定UI成敗。網上有類似的教程,先總結一下,本例以label控件貼圖實現變化顯示,具體實現過程如下:
 
1.       新建工程time.pro
 
2.       使用QDesigner打開time.ui,依次向其中添加8label控件,依次更改ObjectNamehour1hour2label1min1min2label2sec1sec2label1label2更改顯示文字爲“:”,保存,編譯。此時在ui_time.h中會看到聲明並初始化的QLabel控件;以便在後期使用;
 
3.       在項目中新建一個文件夾png,用於存放貼圖;(網上可找到);新建一個Qt Resource file;加入文件夾中的貼圖;此時準備工作做完
 
4.       time.h文件中加入以下語句:
private slots:

void setTime();

private:

QString getpng(QChar x);

 
5.       time.cpp文件中加入以下語句:
#include <QTime>

#include <QTimer>

#include <QPixmap>

構造函數中加入:
QTimer *timer = new QTimer(this);

    timer->setInterval(1000);

    QObject::connect(timer,SIGNAL(timeout()),this,SLOT(setTime()));

timer->start();

獲取貼圖的私有函數定義如下:

QString time::getpng(QChar x)

    {

     return(x+QString(".png"));

 }

槽函數的定義如下:

void time::setTime()

{

    QTime now = QTime::currentTime();

    QString when = now.toString("hh:mm:ss");

    ui.hour1->setPixmap(QPixmap("./png/"+this->getpng(when[0])));

    ui.hour2->setPixmap(QPixmap("./png/"+this->getpng(when[1])));

    ui.min1->setPixmap(QPixmap("./png/"+this->getpng(when[3])));

    ui.min2->setPixmap(QPixmap("./png/"+this->getpng(when[4])));

    ui.sec1->setPixmap(QPixmap("./png/"+this->getpng(when[6])));

    ui.sec2->setPixmap(QPixmap("./png/"+this->getpng(when[7])));

}

PS:如果使用QPushButton做顯示部件,此處函數應該使用ui.hour1->setIcon();

6.顯示效果()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章