1. 程式人生 > >Qt5主視窗狀態列顯示時間

Qt5主視窗狀態列顯示時間

使用Qt Creator建立預設的窗體程式後,主視窗QMainWindow有statusBar狀態列,在此狀態列實時顯示時間可以使用下面方法實現:

mainwindow.h檔案內容:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <mydialog.h>
#include <QLabel>
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_actionNew_Window_triggered();
    void time_update(); //時間更新槽函式,狀態列顯示時間

private:
    Ui::MainWindow *ui;
    QLabel *currentTimeLabel; // 先建立一個QLabel物件
    MyDialog *mydialog;

};

#endif // MAINWINDOW_H

mainwindow.c檔案內容:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "mydialog.h"
#include <QLabel>
#include <QDateTime>
#include <QTimer>
#include <QString>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    currentTimeLabel = new QLabel; // 建立QLabel控制元件
    ui->statusBar->addWidget(currentTimeLabel); //在狀態列新增此控制元件
    QTimer *timer = new QTimer(this);
    timer->start(1000); //每隔1000ms傳送timeout的訊號
    connect(timer, SIGNAL(timeout()),this,SLOT(time_update()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actionNew_Window_triggered()
{
    mydialog = new MyDialog;
    mydialog->show();
}

void MainWindow::time_update()
{
    //[1] 獲取時間
    QDateTime current_time = QDateTime::currentDateTime();
    QString timestr = current_time.toString( "yyyy年MM月dd日 hh:mm:ss"); //設定顯示的格式

    currentTimeLabel->setText(timestr); //設定label的文字內容為時間

}

在這裡插入圖片描述