Qt5主窗口状态栏显示时间

本文介绍如何在QtCreator创建的QMainWindow中实现实时显示当前时间的状态栏。通过在mainwindow.h和mainwindow.cpp文件中添加QLabel和QTimer组件,并连接time_update()槽函数,每秒更新状态栏的时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

}

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值