Qt 在状态栏显示当前时间

本文最后更新于:2021年2月10日 下午

本例主要学习一下怎么在状态栏显示当前时间,主要用的的控件有状态栏(statusbar)、定时器(QTimer)、日期时间库(QDateTime)的使用。

mainwindow.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QLabel>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();

private:
Ui::MainWindow *ui;

private:
QLabel * currentTimeLabel;

private:
void toolbarInit(void);
void userInit(void);

private slots:
void toggleToolBar(bool checked);
void timeUpdate(void);
};
#endif // MAINWINDOW_H

mainwindow.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime>
#include <QTimer>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowIcon(QIcon(":/images/logo.ico"));
userInit();

}

MainWindow::~MainWindow()
{
delete ui;
}

void MainWindow::userInit(void){
// 工具栏显示/隐藏
connect(ui->actionToggleToolBar, &QAction::toggled, this, &MainWindow::toggleToolBar);

// 定义一个定时器
QTimer * timer = new QTimer(this);
timer->start(1000);
// 给 currentTimeLabel 指针新建一个指向对象
currentTimeLabel = new QLabel;
// 给状态栏添加 Widget
ui->statusbar->addWidget(currentTimeLabel);
// 链接信号与槽
connect(timer, &QTimer::timeout, this, &MainWindow::timeUpdate);


}

// **************************************
// 用户定义的槽函数区域
// **************************************

// 工具栏显示/隐藏切换槽函数
void MainWindow::toggleToolBar(bool checked){
ui->toolBar->setVisible(checked);
}

// 时间更新槽函数
void MainWindow::timeUpdate(void){
static int a = 0;
qDebug() << a++ << Qt::endl;

QDateTime current_time = QDateTime::currentDateTime();
QString timestr = current_time.toString("yyyy年MM月dd日 hh:mm:ss");
currentTimeLabel->setText(timestr);
}

// **************************************
// 用户槽函数区域结束
// **************************************

qt-statusbar-timer.gif