Qt添加窗口边框阴影

转载于:https://www.cnblogs.com/SaveDictator/articles/7497462.html

将边框四周添加阴影效果,除了 通过PS这种非常规手段外,还有两种方法(欢迎补充)。实现效果如下:

方法一:通过QFrame + QGraphicsDropShadowEffect方式

复制代码
QFrame *frame = new QFrame(this);
frame->setStyleSheet("QFrame{border-radius:10px}"); //设置圆角与背景透明
frame->setGeometry(5, 5, this->width() - 5, this->height() - 5);//设置有效范围框
QGraphicsDropShadowEffect *shadow_effect = new QGraphicsDropShadowEffect(this);
shadow_effect->setOffset(0, 0);
shadow_effect->setColor(Qt::black);
shadow_effect->setBlurRadius(10);
frame->setGraphicsEffect(shadow_effect);
//...
this->setAttribute(Qt::WA_TranslucentBackground);//特别注意这句
//如果发现没有效果,那可能你设置了底层布局的问题。因为你可能设置了底层布局setContentsMargins的关系,如是,调整这个函数的参数即可
复制代码

方法二。通过paintEvent()函数

复制代码
void DropShadowWidget::paintEvent(QPaintEvent *event)
{
    QPainterPath path;
    path.setFillRule(Qt::WindingFill);
    path.addRect(10, 10, this->width()-20, this->height()-20);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.fillPath(path, QBrush(Qt::white));

    QColor color(0, 0, 0, 50);
    for(int i=0; i<10; i++)
    {
        QPainterPath path;
        path.setFillRule(Qt::WindingFill);
        path.addRect(10-i, 10-i, this->width()-(10-i)*2, this->height()-(10-i)*2);
        color.setAlpha(150 - qSqrt(i)*50);
        painter.setPen(color);
        painter.drawPath(path);
    }
}

//仍然要设置主窗体的背景透明
复制代码

ps:这两种方法,都需要注意两点。其一是设置主窗体的背景透明this->setAttribute(Qt::WA_TranslucentBackground);其二是注意阴影的尺寸

原文地址:https://www.cnblogs.com/tingtaishou/p/14735732.html