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

相关推荐
Hankin_Liu的技术研究室1 小时前
深入理解 C++ happens-before:高级并发程序员的必修课
c++
liu****1 小时前
20.哈希
开发语言·数据结构·c++·算法·哈希算法
爱和冰阔落1 小时前
【C++多态】虚函数/虚表机制与协变 、override和final关键字全解析
开发语言·c++·面试·腾讯云ai代码助手
码住懒羊羊1 小时前
【C++】stack|queue|deque
java·开发语言·c++
“αβ”1 小时前
了解“网络协议”
linux·服务器·网络·c++·网络协议·tcp/ip·tcp
恒者走天下2 小时前
选cpp /c++方向工作职业发展的优缺点
c++
一匹电信狗2 小时前
【LeetCode_160】相交链表
c语言·开发语言·数据结构·c++·算法·leetcode·stl
曦樂~2 小时前
【Qt】信号与槽(Signal and Slot)- 简易计算器
开发语言·数据库·qt
AA陈超3 小时前
虚幻引擎5 GAS开发俯视角RPG游戏 P05-11 消息小部件
c++·游戏·ue5·游戏引擎·虚幻
再卷也是菜3 小时前
C++篇(14)二叉树进阶算法题
c++·算法