Qt 定时消失提示框 淡入淡出提示框

前言

  在实际开发过程中,我们有时需要显示一些信息,这些信息会在短时间后自动消失,而不需要用户手动关闭。为了处理这种需求,我开发了一个自动消失的提示框类。这样做旨在提高开发效率,并为大家提供一个可直接使用或参考的解决方案,如果有任何改进意见,非常欢迎大家提出。

效果展示

请添加图片描述

UML 类图

请添加图片描述

实现思路

  AutoDisapperMsgBox 类继承自 QLabel,利用 QPropertyAnimation 和 QGraphicsOpacityEffect 类来实现动态的显示和消失效果。

代码展示

下面是 autodisappermsgbox.h 的代码

#ifndef AUTODISAPPERMSGBOX_H
#define AUTODISAPPERMSGBOX_H

#include <QObject>
#include <QWidget>
#include <QLabel>

class QGraphicsOpacityEffect;
class QPropertyAnimation;
class QMutex;

class AutoDisapperMsgBox : public QLabel
{
    Q_OBJECT
public:

    explicit AutoDisapperMsgBox(QWidget *parent, const QString& text = "", quint32 displayTime = 3, quint32 fadeOutTime = 3, quint32 fadeInTime = 1);

    void setDuration(quint32 secs);                                         // 设置显示时间

    void setFadeInTime(quint32 secs);                                       // 设置淡入时间

    void setFadeOutTime(quint32 secs);                                      // 设置淡出时间

    void setBackgroundColor(const QColor& color);                           // 设置背景色

    void setRadiusPixel(quint32 pixel);                                     // 设置圆角情况

    void moveToCenterOfParent();                                            // 移动至父对象中心

    void show();

    static void show(QWidget* parent, const QString& text);

private:
    void InitParam();                                                       // 初始化参数

    void InitUI();                                                          // 初始化 UI 界面

    inline QString qColorToStyleSheetRGBA(const QColor& color);             // 将 QColor 转换成 rgba() 格式

    void fadeOut();                                                         // 执行淡出操作
    void fadeIn();                                                          // 执行淡入操作

    void moveToCenterOfParent_p();                                          // 移动至父对象中心

private:
    QGraphicsOpacityEffect* m_opacity = nullptr;                            // 消息框的不透明度
    QPropertyAnimation* m_fadeInAnim = nullptr, *m_fadeOutAnim = nullptr;   // 淡入动画 和 淡出动画
    quint32 m_fadeInTime;                       // 淡入时间
    quint32 m_fadeOutTime;                      // 淡出时间
    quint32 m_displayTime;                      // 显示时间
    QString m_content;                          // 文本
    quint32 m_radiusPix;                        // 圆角值
    QString m_backgroundRGBA;                   // 背景色的RGBA值
    bool m_isAlignCenterOfParent = false;       // 是否位于父对象的中心

    static AutoDisapperMsgBox* mP_instance;     // 静态实例
    static QMutex m_mutex;                      // 锁
};

#endif // AUTODISAPPERMSGBOX_H

下面是 autodisappermsgbox.cpp 的代码

#include "autodisappermsgbox.h"

#include <QGraphicsOpacityEffect>
#include <QPropertyAnimation>
#include <QTimer>
#include <QMutex>
#include <QMutexLocker>

AutoDisapperMsgBox* AutoDisapperMsgBox::mP_instance = nullptr;
QMutex AutoDisapperMsgBox::m_mutex;

AutoDisapperMsgBox::AutoDisapperMsgBox(QWidget *parent, const QString &text, quint32 displayTime, quint32 fadeOutTime, quint32 fadeInTime):
    QLabel(parent),
    m_content(text)
{    
    InitParam();
    InitUI();

    setFadeInTime(fadeInTime);
    setFadeOutTime(fadeOutTime);
    setDuration(displayTime);
}

void AutoDisapperMsgBox::setDuration(quint32 secs)
{
    if(m_displayTime <=0){
        return;
    }
    m_displayTime = secs * 1000;
}

void AutoDisapperMsgBox::setFadeInTime(quint32 secs)
{
    m_fadeInTime = secs * 1000;

    if(m_fadeInAnim){
        m_fadeInAnim->setDuration(static_cast<int>(m_fadeInTime));
    }
}

void AutoDisapperMsgBox::setFadeOutTime(quint32 secs)
{
    m_fadeOutTime = secs * 1000;

    if(m_fadeOutAnim){
        m_fadeOutAnim->setDuration(static_cast<int>(m_fadeOutTime));
    }
}


void AutoDisapperMsgBox::setBackgroundColor(const QColor &color)
{
    m_backgroundRGBA = qColorToStyleSheetRGBA(color);
}

void AutoDisapperMsgBox::setRadiusPixel(quint32 pixel)
{
    m_radiusPix = pixel;
}


void AutoDisapperMsgBox::moveToCenterOfParent()
{
    QWidget* parent =  qobject_cast<QWidget*>(this->parent());

    if(nullptr == parent){
        return;
    }

    m_isAlignCenterOfParent = true;
}

void AutoDisapperMsgBox::show()
{
    this->setText(m_content);

    // 设置样式表
    QString styleSheet = QString("QLabel{color:white;"
                                 "background-color:%1; border-radius:%2;}").arg(m_backgroundRGBA).arg(m_radiusPix);
    this->setStyleSheet(styleSheet);

    // 如果移动至父对象中间标志已置为true,则执行下面的代码
    if(m_isAlignCenterOfParent){
        moveToCenterOfParent_p();
    }

    // 淡入
    fadeIn();

    QLabel::show();
}

void AutoDisapperMsgBox::show(QWidget *parent, const QString &text)
{
    if(nullptr == parent){
        return;
    }

    if(nullptr == mP_instance){
        // 双重检验
        QMutexLocker locker(&m_mutex);
        if(nullptr == mP_instance){
            mP_instance = new AutoDisapperMsgBox(parent, text);
        }
    }else{
        mP_instance->setParent(parent);
        mP_instance->m_content = text;
    }

    if(nullptr == mP_instance){
        return;
    }

    mP_instance->moveToCenterOfParent();

    mP_instance->show();
}


void AutoDisapperMsgBox::InitParam()
{
    m_opacity = new QGraphicsOpacityEffect(this);

    // 将 m_opacity 设置为 QLabel 的 GraphicsEffect
    this->setGraphicsEffect(m_opacity);

    m_fadeInAnim = new QPropertyAnimation(m_opacity, "opacity");
    m_fadeOutAnim = new QPropertyAnimation(m_opacity, "opacity");

    // 设置淡入淡出的属性起始值
    m_fadeInAnim->setStartValue(0);
    m_fadeInAnim->setEndValue(1);

    m_fadeOutAnim->setStartValue(1);
    m_fadeOutAnim->setEndValue(0);

}

void AutoDisapperMsgBox::InitUI()
{
    // 此处为默认样式,可被修改
    this->setMinimumSize(100,38);
    this->setAlignment(Qt::AlignCenter);
    setBackgroundColor(QColor(0, 0, 0, 150));
    setRadiusPixel(15);    
}

QString AutoDisapperMsgBox::qColorToStyleSheetRGBA(const QColor &color)
{

    return QString("rgba(%1, %2, %3, %4)")
           .arg(color.red())    // 获取红色分量
           .arg(color.green())  // 获取绿色分量
           .arg(color.blue())   // 获取蓝色分量
           .arg(color.alpha()); // 获取透明度分量

}

void AutoDisapperMsgBox::fadeOut()
{
    if(m_fadeOutAnim && m_fadeOutAnim->state() != QPropertyAnimation::Running){
        m_fadeOutAnim->start();
        connect(m_fadeOutAnim, &QPropertyAnimation::finished, this, [this](){
           this->hide();
        });
    }
}

void AutoDisapperMsgBox::fadeIn()
{
    // 如果淡入动画没有运行,则执行下面的代码
    if(m_fadeInAnim && m_fadeInAnim->state() != QPropertyAnimation::Running){
        m_fadeInAnim->start();

        connect(m_fadeInAnim, &QPropertyAnimation::finished, this, [this](){
            QTimer::singleShot(m_displayTime, [this](){
                fadeOut();
            });
        }, Qt::UniqueConnection);

    }

}

void AutoDisapperMsgBox::moveToCenterOfParent_p()
{
    QWidget* parent =  qobject_cast<QWidget*>(this->parent());

    if(nullptr == parent){
        return;
    }

    // 计算中心位置
    int x = (parent->size().width() - this->width()) / 2;
    int y = (parent->size().height() - this->height()) / 2;

    // 将按钮移动到中心
    this->move(x, y);
}

下面是两种使用方式


// 方式一:静态展示
	AutoDisapperMsgBox::show(this, "开机中...");

// 方式二:自定义展示
    AutoDisapperMsgBox msgBox = new AutoDisapperMsgBox(this);
    msgBox->setDuration(5);
    msgBox->setFadeInTime(2);
    msgBox->setText("关机中… ");
    msgBox->resize(300,50);
    msgBox->show();
    
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值