【C++/Qt】QLCDNumber-电子时钟实战

发布时间 2024-01-11 14:19:50作者: wshidaboss

头文件:

#ifndef DIGITALCLOCK_H
#define DIGITALCLOCK_H
#include <QLCDNumber>

class digitalClock : public QLCDNumber
{
    Q_OBJECT
public:
    digitalClock(QWidget *parent = 0);
protected:
    void mousePressEvent(QMouseEvent *event);//鼠标点击事件
    void mouseMoveEvent(QMouseEvent *event);//鼠标移动事件
private slots:
    void showTime();//显示时间
private:
    QPoint m_dragPosition;//保存鼠标点相对于钟表左上角的偏移值
    bool m_showColon;//钟表显示:
};

#endif // DIGITALCLOCK_H

cpp文件:

#include "digitalclock.h"
#include <QTimer>
#include <QTime>
#include <QMouseEvent>
digitalClock::digitalClock(QWidget *parent):QLCDNumber(parent)
{
    setWindowFlags(Qt::FramelessWindowHint);//无边框窗体风格

    //设置蓝色背景
    QPalette p = palette();
    p.setColor(QPalette::Window,Qt::blue);
    setPalette(p);

    //设置窗体透明度
    setWindowOpacity(0.5);

    //创建并打开计时器
    QTimer *timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,&digitalClock::showTime);
    timer->start(1000);

    showTime();
    resize(150,60);//设置窗口大小
    m_showColon = true;
}

void digitalClock::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton){
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        //鼠标相对屏幕左上角的位置 - 时钟窗体左上角的位置
        event->accept();
    }
    if(event->button() == Qt::RightButton){//当点击鼠标右键时关闭窗口
        close();
    }
}

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

void digitalClock::showTime()
{
    QTime time = QTime::currentTime();//获取当前时间
    QString strTime = time.toString("hh:mm");//把获取的时间转化为字符串
    if(m_showColon){
        strTime[2]=':';
    }else{
        strTime[2]=' ';
    }
    display(strTime);//显示时间
    m_showColon = !m_showColon;
}

运行结果: