Qt 窗口阴影效果的实现

前言

今天正好搞一下窗口的阴影,发现一篇文章写的真是不错。毫不犹豫滴转过来了,感谢作者分享。

转自:http://blog.sina.com.cn/s/blog_a6fb6cc90101eoop.html

正题

前面就窗口阴影已经写过一篇博客,使用九宫格的思路实现的,在我看来,凡是用程序能实现的尽量不要使用图片代替(在保证效率的前提下),今天再次分享关于我的一些小见解!

先看效果:

img

img

窗口阴影任意调节,包括阴影像素、是否圆角等。直接上代码:

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

记得加上这行代码:

setAttribute(Qt::WA_TranslucentBackground);

保证不被绘制上的部分透明,关于这行代码在一些Qt版本中会有副作用。

比如:最小化后窗体子组件失去焦点等问题。具体可以看Qt的这个Bug

(Widget with Qt::FramelessWindowHint and Qt::WA_TranslucentBackground stops painting after minimize/restore)

一直使用的是VS集成Qt5插件(非OpenGL版本),一直存在这个问题,寻找各方面资料无果(真的很久,搞不夸张的说大半年应该是有的)。最后改换OpenGL版本的居然好了。。。问题的解决方式太过于诡异,真让人哭笑不得。在此记过,希望对后来人有帮助。

为子部件添加阴影

QGraphicsDropShadowEffect *shadow_effect = new QGraphicsDropShadowEffect(this);
shadow_effect->setOffset(-5, 5);
shadow_effect->setColor(Qt::gray);
shadow_effect->setBlurRadius(8);
network_group_box->setGraphicsEffect(shadow_effect);

效果如下:

img

posted @ 2020-11-27 15:13  FreeK0x00  阅读(2435)  评论(1编辑  收藏  举报