1、QGraphicsDropShadowEffect
setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground);
QGraphicsDropShadowEffect *effect = new QGraphicsDropShadowEffect();
effect->setBlurRadius(20);
effect->setColor(QColor::fromRgbF(0, 0, 0, 0.7));
effect->setOffset(0, 0);
setGraphicsEffect(effect);
该方法会导致设置了QGraphicsDropShadowEffect的QOpenGLWidget类型子窗口不显示(好像是Qt的Bug),所以当界面用到QOpenGLWidget时,最好使用下面的方法。
2、QPainter 绘制
如第一种方法,窗口也需要设置为背景透明的。
void paintEvent(QPaintEvent *event)
{
if (isMaximized())
{
return;
}
int nShadowsWidth = 6;
int nRadius = 3;
QPainterPath path;
path.setFillRule(Qt::WindingFill);
path.addRoundedRect(nShadowsWidth, nShadowsWidth, this->width() - nShadowsWidth * 2, this->height() - nShadowsWidth * 2, nRadius, nRadius);
QPainter painter(this);
QColor color(0, 0, 0, 200);
for (int i = 0; i < nShadowsWidth; i++)
{
QPainterPath path;
path.setFillRule(Qt::WindingFill);
path.addRoundedRect(nShadowsWidth - i, nShadowsWidth - i, this->width() - (nShadowsWidth - i) * 2, this->height() - (nShadowsWidth - i) * 2, nRadius + i, nRadius + i);
color.setAlpha(100 - qSqrt(i) * 50);
painter.setPen(color);
painter.drawPath(path);
}
}