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的文本内容为时间
}


リファレンスブログ:
Qtは現在の時刻を取得します(非常に詳細)
QTインターフェイスは現在の日付と時刻をリアルタイムで表示します

おすすめ

転載: blog.csdn.net/qq_39400113/article/details/114881683