溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Qt5如何實(shí)現(xiàn)主窗口狀態(tài)欄顯示時(shí)間

發(fā)布時(shí)間:2021-03-18 10:05:50 來(lái)源:億速云 閱讀:420 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)Qt5如何實(shí)現(xiàn)主窗口狀態(tài)欄顯示時(shí)間的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。

使用Qt Creator創(chuàng)建默認(rèn)的窗體程序后,主窗口QMainWindow有statusBar狀態(tài)欄,在此狀態(tài)欄實(shí)時(shí)顯示時(shí)間可以使用下面方法實(shí)現(xiàn):

mainwindow.h文件內(nèi)容:

#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(); //時(shí)間更新槽函數(shù),狀態(tài)欄顯示時(shí)間
private:
  Ui::MainWindow *ui;
  QLabel *currentTimeLabel; // 先創(chuàng)建一個(gè)QLabel對(duì)象
  MyDialog *mydialog;
};
#endif // MAINWINDOW_H

mainwindow.c文件內(nèi)容:

#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; // 創(chuàng)建QLabel控件
  ui->statusBar->addWidget(currentTimeLabel); //在狀態(tài)欄添加此控件
  QTimer *timer = new QTimer(this);
  timer->start(1000); //每隔1000ms發(fā)送timeout的信號(hào)
  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] 獲取時(shí)間
  QDateTime current_time = QDateTime::currentDateTime();
  QString timestr = current_time.toString( "yyyy年MM月dd日 hh:mm:ss"); //設(shè)置顯示的格式
  currentTimeLabel->setText(timestr); //設(shè)置label的文本內(nèi)容為時(shí)間
}

Qt5如何實(shí)現(xiàn)主窗口狀態(tài)欄顯示時(shí)間

補(bǔ)充:Qt 通過(guò)QLabel控件來(lái)顯示實(shí)時(shí)日期時(shí)間

頭文件需添加:

#include <QTimer>

構(gòu)造函數(shù)中:

//日期/時(shí)間顯示
QTimer *timer = new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(timerUpdate()));
timer->start(1000);

定義成員函數(shù)timerUpdate()實(shí)現(xiàn)用戶界面顯示時(shí)間:

void userwindow::timerUpdate()
{
  QDateTime time = QDateTime::currentDateTime();
  QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd");
  ui->dateTime->setText(str);
}

感謝各位的閱讀!關(guān)于“Qt5如何實(shí)現(xiàn)主窗口狀態(tài)欄顯示時(shí)間”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

qt5
AI