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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM