Qt QDate QTime顯示當前系統時間

寫給逗比的信發表於2014-11-17

   QDate date = QDate::currentDate();   //獲取當前日期
   QTime time = QTime::currentTime();   //獲取當前時間

效果如下:



#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QLabel>
#include <QTimer>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
private slots:
    void ClockTimeout();
private:
    QLabel      *mpSecond;          //當前秒數
    QLabel      *mpDate;            //日期 年月日
    QLabel      *mpHourMin;         //時分
    QTimer      *timer;

};

#endif // MAINWINDOW_H

#include "mainwindow.h"
#include <QDate>
#include <QTime>
#include <QString>
#include <QHBoxLayout>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    this->setFixedSize(300,50);
    
    QWidget *bgd = new QWidget; //設定背景
    bgd->setObjectName("bgd");
    this->setCentralWidget(bgd); 
    bgd->setStyleSheet("QWidget#bgd{background: qlineargradient(x1:0, y1:0, x2:1, y2:1,\
                       stop:0 white, stop: 0.4 gray, stop:1 green)}");
    
    QHBoxLayout *hLayout  = new QHBoxLayout;  //水平不拒
    hLayout->setContentsMargins(0,0,0,0);
    hLayout->setSpacing(0);

    mpDate = new QLabel;
    mpHourMin = new QLabel;
    mpSecond  = new QLabel;

    mpSecond->setAlignment(Qt::AlignBottom);
    mpDate->setAlignment(Qt::AlignBottom);
    mpHourMin->setAlignment(Qt::AlignBottom);

    //設定字型
    mpDate->setStyleSheet("font-size:20px;color:white;background-color:transparent");
    mpSecond->setStyleSheet("font-size:20px;color:white;background-color:transparent");
    mpHourMin->setStyleSheet("font-size:30px;color:white;background-color:transparent");

    hLayout->addStretch();\
    hLayout->addWidget(mpHourMin);
    hLayout->addSpacing(10);
    hLayout->addWidget(mpSecond);
    hLayout->addSpacing(10);
    hLayout->addWidget(mpDate);
    hLayout->addSpacing(10);
    bgd->setLayout(hLayout);

    timer = new QTimer(this);
    timer->start(1000);
    connect(timer,SIGNAL(timeout()),this,SLOT(ClockTimeout()));


}

void MainWindow::ClockTimeout()
{
   QDate date = QDate::currentDate();   //獲取當前日期
   QTime time = QTime::currentTime();   //獲取當前時間
   mpSecond->setText(":"+time.toString("ss"));
   mpHourMin->setText(time.toString("hh:mm"));
   mpDate->setText(date.toString("yyyy-MM-dd"));
}

MainWindow::~MainWindow()
{

}

相關文章