Qt5主窗口状态栏显示时间

版权声明:本文为博主ouening原创文章,未经博主允许不得恶意复制转载,需要注明出处,尊重知识成果!技术交流请联系[email protected]! https://blog.csdn.net/ouening/article/details/83026779

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

}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ouening/article/details/83026779
今日推荐