使用Qt Creator创建默认的窗体程序后,主窗口QMainWindow有statusBar状态栏,在此状态栏实时显示时间可以使用下面方法实现:
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
|
#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文件内容:
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
|
#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 通过QLabel控件来显示实时日期时间
头文件需添加:
1
|
#include <QTimer> |
构造函数中:
1
2
3
4
|
/ / 日期 / 时间显示 QTimer * timer = new QTimer(this); connect(timer,SIGNAL(timeout()),this,SLOT(timerUpdate())); timer - >start( 1000 ); |
定义成员函数timerUpdate()实现用户界面显示时间:
1
2
3
4
5
6
|
void userwindow::timerUpdate() { QDateTime time = QDateTime::currentDateTime(); QString str = time.toString( "yyyy-MM-dd hh:mm:ss dddd" ); ui - >dateTime - >setText( str ); } |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。
原文链接:https://blog.csdn.net/ouening/article/details/83026779