使用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的文本內容為時間
}

補充:Qt 通過QLabel控件來顯示實時日期時間
頭文件需添加:
構造函數中:
//日期/時間顯示
QTimer *timer = new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(timerUpdate()));
timer->start(1000);
定義成員函數timerUpdate()實現用戶界面顯示時間:
void userwindow::timerUpdate()
{
QDateTime time = QDateTime::currentDateTime();
QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd");
ui->dateTime->setText(str);
}
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- PyQt5 實現狀態欄永久顯示消息
- python GUI庫圖形界面開發之PyQt5狀態欄控件QStatusBar詳細使用方法實例
- python3.x+pyqt5實現主窗口狀態欄里(嵌入)顯示進度條功能