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

相关推荐
CC.GG21 分钟前
【C++】C++11----智能指针
开发语言·c++
星火开发设计35 分钟前
const 指针与指针 const:分清常量指针与指针常量
开发语言·c++·学习·算法·指针·const·知识
闻缺陷则喜何志丹36 分钟前
【树 链 菊花】P10418 [蓝桥杯 2023 国 A] 相连的边|普及+
c++·算法·蓝桥杯···菊花
REDcker41 分钟前
libwebsockets库原理详解
c++·后端·websocket·libwebsockets
天上飞的粉红小猪1 小时前
c++的IO流
开发语言·c++
ygklwyf1 小时前
JPRS编程竞赛2026#1(AtCoder初学者竞赛442)
c++·算法·模拟
王老师青少年编程1 小时前
信奥赛C++提高组csp-s之倍增算法思想及应用(3)
c++·noip·csp·信奥赛·csp-s·提高组·倍增算法
万象.2 小时前
redis客户端安装与实现C++版本
数据库·c++·redis
321.。2 小时前
深入理解 Linux 线程封装:从 pthread 到 C++ 面向对象实现
linux·开发语言·c++
EmbedLinX2 小时前
Linux内核之文件系统:从VFS到实际存储的运作机制
linux·服务器·c语言·c++