基于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、运行效果

相关推荐
橘颂TA5 分钟前
【Linux】从 “抢资源” 到 “优雅控场”:Linux 互斥锁的原理与 C++ RAII 封装实战(Ⅰ)
linux·运维·服务器·c++·算法
赵民勇10 分钟前
Qt项目缺少Quick模块错误解决方案
linux·qt
枫叶丹421 分钟前
【Qt开发】Qt系统(三)->事件过滤器
java·c语言·开发语言·数据库·c++·qt
坐怀不乱杯魂1 小时前
Linux - 缓存利用率
linux·c++·缓存
leiming61 小时前
c++ for_each算法
开发语言·c++·算法
_OP_CHEN1 小时前
【算法基础篇】(四十一)数论之约数问题终极攻略:从求单个约数到批量统计
c++·算法·蓝桥杯·数论·约数·算法竞赛·acm/icpc
草莓熊Lotso1 小时前
从冯诺依曼到操作系统:打通 Linux 底层核心逻辑
linux·服务器·c++·人工智能·后端·系统架构·系统安全
yuanmenghao1 小时前
自动驾驶中间件iceoryx - 内存与 Chunk 管理(一)
c++·vscode·算法·链表·中间件·自动驾驶·柔性数组
艾莉丝努力练剑1 小时前
【QT】初识QT:背景介绍
java·运维·数据库·人工智能·qt·安全·gui
橘颂TA1 小时前
【剑斩OFFER】算法的暴力美学——面试题 01.02 :判定是否互为字符串重排
c++·算法·leetcode·职场和发展·结构与算法