Qt设置窗体背景渐变

方案一: 重写绘图事件,配合

1 setAttribute(Qt::WA_TranslucentBackground);//设置窗体透明(这个时候主窗体是没有颜色的(也不可以设置颜色),一般可设置一个比主窗体小一点的widget放在主窗体里,然后设置widget的颜色)
 1 void Login::paintEvent(QPaintEvent *)
 2 {
 3     QPainter painter(this);
 4     painter.setRenderHint(QPainter::Antialiasing, true);
 5 
 6     QColor color(Qt::black);
 7     for(int i=0; i<=5; i++)
 8     {
 9        QPainterPath path;
10        path.setFillRule(Qt::WindingFill);
11        path.addRect(5-i, 5-i, this->width()-(5-i)*2, this->height()-(5-i)*2);
12        color.setAlpha(150-qSqrt(i)*50);//通过改变颜色透明度达到渐变效果
13        painter.setPen(color);
14        painter.drawPath(path);
15     }
16 }

方案二: 使用QGraphicsDropShadowEffect,配合setAttribute(Qt::WA_TranslucentBackground)和setWindowFlags(Qt::FramelessWindowHint)使用

(一般可设置一个比主窗体小一点的widget放在主窗体里,然后设置widget的颜色和圆角等)

1 QGraphicsDropShadowEffect *shadow=new QGraphicsDropShadowEffect(this);
2 shadow->setOffset(0);
3 shadow->setBlurRadius(20);
4 shadow->setColor(Qt::red);
5 this->setGraphicsEffect(shadow);
原文地址:https://www.cnblogs.com/YLJ666/p/14615071.html