欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > 基于QT和C++的实时日期和时间显示

基于QT和C++的实时日期和时间显示

2025/7/1 20:25:06 来源:https://blog.csdn.net/m0_69119438/article/details/145033317  浏览:    关键词:基于QT和C++的实时日期和时间显示

一、显示在右下角

1、timer.cpp

#include "timer.h"
#include "ui_timer.h"
#include <QStatusBar>
#include <QDateTime>
#include <QMenuBar>
Timer::Timer(QWidget *parent) :QMainWindow(parent),ui(new Ui::Timer)
{ui->setupUi(this);// 创建状态栏QStatusBar *statusBar = new QStatusBar(this);this->setStatusBar(statusBar);// 创建用于显示时间的标签timeLabel = new QLabel(this);statusBar->addPermanentWidget(timeLabel);// 创建计时器,每秒更新一次timer = new QTimer(this);connect(timer, &QTimer::timeout, this, &Timer::updateTime);timer->start(1000); // 设置每1000毫秒(1秒)触发一次// 初始化时间显示updateTime();
}
Timer::~Timer()
{delete ui;
}
void Timer::updateTime()
{timeLabel->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
}

2、timer.h

#ifndef TIMER_H
#define TIMER_H#include <QMainWindow>
#include <QTimer>
#include <QLabel>namespace Ui {
class Timer;
}
class Timer : public QMainWindow
{Q_OBJECT
public:explicit Timer(QWidget *parent = nullptr);~Timer();
private slots:void updateTime();
private:Ui::Timer *ui;QTimer *timer;QLabel *timeLabel;
};
#endif

3、 演示效果

二、显示在左上角

1、timer.cpp

#include "timer.h"
#include "ui_timer.h"
#include <QMenuBar>
#include <QDateTime>
#include <QTimer>Timer::Timer(QWidget *parent) :QMainWindow(parent),ui(new Ui::Timer)
{ui->setupUi(this);// 创建菜单栏menuBar = new QMenuBar(this);setMenuBar(menuBar);// 创建一个动作来显示时间timeAction = new QAction(this);timeAction->setText("00:00:00");menuBar->addAction(timeAction);// 创建计时器,每秒更新一次timer = new QTimer(this);connect(timer, &QTimer::timeout, this, [this](){timeAction->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));});timer->start(1000); // 设置每1000毫秒(1秒)触发一次
}Timer::~Timer()
{delete ui;
}

2、timer.h

#ifndef TIMER_H
#define TIMER_H#include <QMainWindow>
#include <QTimer>
#include <QMenuBar>namespace Ui {
class Timer;
}class Timer : public QMainWindow
{Q_OBJECTpublic:explicit Timer(QWidget *parent = nullptr);~Timer();private:Ui::Timer *ui;QTimer *timer;QMenuBar *menuBar;QAction *timeAction; // 添加这个成员变量
};#endif

3、运行效果

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词