獲取系統時間並動態顯示

       本例以按鍵作爲顯示部件(即獲取到系統時間後顯示在按鈕上),使用定時器timer,每隔1s產生timeout()的信號,使用信號槽機制,實現button顯示系統時間; 使用connect(timer,SIGNAL(timeout()),this,SLOT(setTime()));   關聯定時器信號與相應的槽函數
 
1.       建立工程dateTime.Pro
2.       具體代碼:
dateTime.h文件中添加:
#include <QPushButton>

private slots:

    void setTime();

private:

QPushButton* button;

dateTime.cpp文件中添加:

#include <QTimer>

#include <QDateTime>

在構造函數中添加

//setWindowFlags(Qt::FramelessWindowHint);   
                    //設置窗體無邊框
button = new QPushButton(this);             
                       //實例化一個按鈕

    button->setGeometry(0,0,400,300);           
                       //設置按鈕的尺寸

    QTimer *timer = new QTimer(this);          
                       //實例化一個定時器

    timer->setInterval(1000);                 
                       //設置定時器間隔爲1S

    QObject::connect(timer,SIGNAL(timeout()),this,SLOT(setTime()));         
                       //關聯定時器與槽函數

    timer->start(); 
                       //計時開始
        在槽函數 void dateTime::setTime()中添加
   QDateTime dateTime = QDateTime::currentDateTime();
                       //獲取當前時間

button->setText(dateTime.toString("yyyy-MM-dd hh:mm:ss dddd"));

                    //設置按鈕上顯示的內容格式

或者:

QDateTime dateTime = QDateTime::currentDateTime();

    int year = dateTime.date().year();

    int month = dateTime.date().month();

    int day = dateTime.date().day();

    QString time = dateTime.time().toString("hh:mm:ss");

button->setText(time+" "+QString::number(year)+"/"+QString::

number(month) +"/"+QString::number(day));

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