After using Qt Creator to create the default form program, the main window QMainWindow has statusBar, in this status bar real-time display time can be achieved using the following method:
File contents:
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <> #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(); // Time update slot function, status bar display time private: Ui::MainWindow *ui; QLabel *currentTimeLabel; // Create a QLabel object first MyDialog *mydialog; }; #endif // MAINWINDOW_H
File contents:
#include "" #include "ui_mainwindow.h" #include "" #include <QLabel> #include <QDateTime> #include <QTimer> #include <QString> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); currentTimeLabel = new QLabel; // Create the QLabel control ui->statusBar->addWidget(currentTimeLabel); // Add this control to the status bar QTimer *timer = new QTimer(this); timer->start(1000); //Send the timeout signal every 1000ms. 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] Getting the time QDateTime current_time = QDateTime::currentDateTime(); QString timestr = current_time.toString( "yyyysurname NianMMmoondddate hh:mm:ss"); //Set the format of the display currentTimeLabel->setText(timestr); //Set the text content of the label to the time. }
Supplementary: Qt to display real-time date and time via QLabel control
Header files need to be added:
#include <QTimer>
in the constructor:
//Date/Time Display QTimer *timer = new QTimer(this); connect(timer,SIGNAL(timeout()),this,SLOT(timerUpdate())); timer->start(1000);
Define the member function timerUpdate() to implement the user interface to display the time:
void userwindow::timerUpdate() { QDateTime time = QDateTime::currentDateTime(); QString str = ("yyyy-MM-dd hh:mm:ss dddd"); ui->dateTime->setText(str); }
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more. If there is any mistake or something that has not been fully considered, please do not hesitate to give me advice.