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

一、显示在右下角

1、timer.cpp

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

cpp 复制代码
#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

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

cpp 复制代码
#ifndef TIMER_H
#define TIMER_H

#include <QMainWindow>
#include <QTimer>
#include <QMenuBar>

namespace Ui {
class Timer;
}

class Timer : public QMainWindow
{
    Q_OBJECT

public:
    explicit Timer(QWidget *parent = nullptr);
    ~Timer();

private:
    Ui::Timer *ui;
    QTimer *timer;
    QMenuBar *menuBar;
    QAction *timeAction; // 添加这个成员变量
};

#endif

3、运行效果

相关推荐
hardStudy_h13 分钟前
C++——内联函数与Lambda表达式
开发语言·jvm·c++
ZZZS05161 小时前
stack栈练习
c++·笔记·学习·算法·动态规划
位东风1 小时前
【c++学习记录】状态模式,实现一个登陆功能
c++·学习·状态模式
雷羿 LexChien3 小时前
C++内存泄漏排查
开发语言·c++
嘉小华4 小时前
CMake 完全指南:第一章 - 构建的烦恼 - 为什么需要CMake?
c++
Feliz Da Vida4 小时前
[代码学习] c++ 通过H矩阵快速生成图像对应的mask
c++·学习
无聊的小坏坏5 小时前
单调栈通关指南:从力扣 84 到力扣 42
c++·算法·leetcode
YOLO大师5 小时前
华为OD机试 2025B卷 - 小明减肥(C++&Python&JAVA&JS&C语言)
c++·python·华为od·华为od机试·华为od2025b卷·华为机试2025b卷·华为od机试2025b卷
看到我,请让我去学习7 小时前
OpenCV编程- (图像基础处理:噪声、滤波、直方图与边缘检测)
c语言·c++·人工智能·opencv·计算机视觉
钢铁男儿8 小时前
PyQt5高级界而控件(容器:装载更多的控件QDockWidget)
数据库·python·qt