Qt实现shadow显得有层次感

目的

如何实现Qt窗口周围有阴影显得有层次感。 很多人第一部分就是

setWindowFlags(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground);

QGraphicsDropShadowEffect *effect = new QGraphicsDropShadowEffect(this);
effect->setOffset(0, 0);          //设置向哪个方向产生阴影效果(dx,dy),特别地,(0,0)代表向四周发散
effect->setColor(Qt::gray);       //设置阴影颜色,也可以setColor(QColor(220,220,220))
effect->setBlurRadius(20);        //设定阴影的模糊半径,数值越大越模糊
ui->mainFrame->setGraphicsEffect(effect);

这样有个问题

警告:第一种绘制的无边框阴影,有可能在遇到大批量控件刷新的时候,报Update Layered Window Indirect failed for ptDst=…这个错误,使得界面刷新卡顿,所以必须使用其他方案,如如下方式直接在painEvent中绘,也可以实现阴影
第二种: 内部子控件由于继承父控件关系, 也会有类似这样效果

综合一二, 只能由painter绘制, 最多算法代码复杂。

代码参考如下:实际效果由ui设计提供, 对应修改
参考

#include 
void LoginDialog::paintEvent(QPaintEvent *event)
{
    
    QPainterPath path;
    path.setFillRule(Qt::WindingFill);
    QRectF rect(10, 10, this->width()-20, this->height()-20);
    path.addRoundRect(rect, 8, 8);

    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);
    }
}

你可能感兴趣的:(qt)