Qt之QGraphicsDropShadowEffect

简述

QGraphicsDropShadowEffect可以为Qt中的控件提供阴影效果。

使用setColor()函数来设置阴影颜色,使用setOffset来设置阴影偏移,使用setBlurRadius()来设置阴影模糊半径。

默认的阴影是半透明黑灰色,1px模糊半径,向右下角8px偏移。

使用

效果

源码

QPushButton pushBtn = new QPushButton("test");
QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect;
shadowEffect->setOffset(5, 5);//设置偏移
shadowEffect->setBlurRadius(5);//设置模糊半径
shadowEffect->setColor(QColor(0, 0, 200, 200));//设置颜色
pushBtn->setStyleSheet("QPushButton {background-color: red}");
pushBtn->setGraphicsEffect(shadowEffect);

QGraphicsDropShadowEffect的使用主要是设置如下三个属性:

  • 横纵偏移量:setOffset()
  • 模糊半径:setBlurRadius()
  • 颜色值:setColor()

使用案例

通过上面的简单的介绍,我们已经掌握了QGraphicsDropShadowEffect的基本用法,下展示一个自定义带阴影样式按钮示例。

QSS是基于CSS2的,默认不带box-shadow属性。下面基于QGraphicsDropShadowEffect来实现带box-shadow属性的按钮控件。

源码

下面是按钮的源码,在设置样式表时要用setQSS(),而不是setStyleSheet(),其余的用法和QPushButton一样。

class MyPushButton : public QPushButton
{
    Q_OBJECT
public:
    MyPushButton(QString str, QWidget *parent = nullptr) : QPushButton(str, parent)
    {
        shadowEffect = new QGraphicsDropShadowEffect;
        setGraphicsEffect(shadowEffect);
    }

    void setQSS(QString str)
    {
        QString pattern = "box-shadow: (.*\\d+)px (.*\\d+)px (\\d+)px rgba\\((\\d+), (\\d+), "
                          "(\\d+), (\\d+)\\);";
        QRegExp *re = new QRegExp(pattern);
        re->indexIn(str);
        QStringList list =  re->capturedTexts();
        qreal dx = list[1].toDouble();
        qreal dy = list[2].toDouble();
        qreal blurRadius = list[3].toDouble();
        int r = list[4].toInt();
        int g = list[5].toInt();
        int b = list[6].toInt();
        int a = list[7].toInt();
        QColor color(r, g, b, a);
        drawShadowEffect(dx, dy, blurRadius, color);
        str.replace(QRegExp(pattern), "");
        setStyleSheet(str);
    }
private:
    QGraphicsDropShadowEffect *shadowEffect;
    void drawShadowEffect(qreal dx, qreal dy, qreal blurRadius, QColor color)
    {
        shadowEffect->setOffset(dx, dy);
        shadowEffect->setBlurRadius(blurRadius);
        shadowEffect->setColor(color);
    }

};

使用

    MyPushButton *btn = new MyPushButton("test");
    btn->setQSS("QPushButton { background-color:red;box-shadow: 5px 5px 5px rgba(0, 0, 200, 200);}");
    QHBoxLayout *hLayout = new QHBoxLayout;
    hLayout->addWidget(btn);

效果

引用

[1] Qt助手

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值