QT QLCDNumber、QTimer,QMouseEvent鼠标事件 实例

本文介绍了一个使用Qt库开发的电子时钟应用,它具有无边框、半透明窗口效果,背景色为蓝色,并通过定时器每秒更新显示系统当前时间。DigiClock类定义了鼠标操作和时间显示功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • QPalette p=palette()、p.setColor(QPalette::Window, Qt::blue)、setPalette§:设置电子时钟窗体背景色。
  • setWindowFlags(Qt::FramelessWindowHint):设置窗体的标识,此处设置窗体为一个没有面板边框和标题栏的窗体。
  • setWindowOpacity(0.5):设置窗体的透明度为0.5,即半透明。
  • QTimer *timer=new QTimer(this):新建一个定时器对象。
  • timer->start(1000):以1000ms为周期启动定时器。
  • resize(150, 60):设置电子时钟显示的尺寸。
  • QTime time = QTime::currentTime():获取当前系统时间,保存在一个QTime对象中。
  • QString text = time.toString(“hh:mm”):把获取的当前时间转换为字符串类型。
  • display(text):显示转换好的字符串时间。

digiclock.h

#ifndef DIGICLOCK_H
#define DIGICLOCK_H

#include <QLCDNumber>
#include <QMouseEvent>
#include <QWidget>

class DigiClock : public QLCDNumber
{
    Q_OBJECT
public:
    DigiClock(QWidget *parent=nullptr);
    ~DigiClock();
    void mousePressEvent(QMouseEvent *);
    void mouseMoveEvent(QMouseEvent *);
private slots:
    void showTime();
private:
    QPoint dragPosition;
    bool showColon;
};

#endif // DIGICLOCK_H

digiclock.cpp

#include "digiclock.h"

#include <QTimer>
#include <QTime>
#include <QMouseEvent>

DigiClock::DigiClock(QWidget *parent):QLCDNumber(parent)
{
    QPalette p = palette();
    p.setColor(QPalette::Window, Qt::blue);
    setPalette(p);

    setWindowFlags(Qt::FramelessWindowHint);

    setWindowOpacity(0.5);

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(showTime()));
    timer->start(1000);
    showTime();
    resize(160, 60);
    showColon=true;

}

DigiClock::~DigiClock()
{

}

void DigiClock::showTime()
{
    QTime time = QTime::currentTime();
    QString text = time.toString("hh:mm");
    if (showColon ){
        text[2]=':';
        showColon = false;
    } else {
        text[2]=' ';
        showColon = true;
    }

    display(text);
}

void DigiClock::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    }
    if (event->button() == Qt::RightButton) {
        close();
    }
}

void DigiClock::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {
        move(event->globalPos() - dragPosition);
        event->accept();
    }
}

main.cpp

#include "digiclock.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    DigiClock clock;
    clock.show();
    return a.exec();
}


在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SongYuLong的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值