这篇文章给大家分享的是有关Qt5如何实现主窗口状态栏显示时间的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
使用Qt Creator创建默认的窗体程序后,主窗口QMainWindow有statusBar状态栏,在此状态栏实时显示时间可以使用下面方法实现:
#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
#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控件来显示实时日期时间
#include <QTimer>
//日期/时间显示
QTimer *timer = new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(timerUpdate()));
timer->start(1000);
定义成员函数timerUpdate()实现用户界面显示时间:
void userwindow::timerUpdate()
{
QDateTime time = QDateTime::currentDateTime();
QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd");
ui->dateTime->setText(str);
}
感谢各位的阅读!关于“Qt5如何实现主窗口状态栏显示时间”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。