qt-添加窗口邊框陰影


將邊框四周添加陰影效果,除了 通過PS這種非常規手段外,還有兩種方法(歡迎補充)。實現效果如下:

 

方法一:通過QFrame + QGraphicsDropShadowEffect方式

QFrame *frame = new QFrame(this);
frame->setStyleSheet("QFrame{background-color: rgb(255, 255, 255);border-radius:10px}"); //設置圓角與背景透明
frame->setGeometry(5, 5, this->width() - 5, this->height() - 5);//設置有效范圍框
QGraphicsDropShadowEffect *shadow_effect = new QGraphicsDropShadowEffect(this);
shadow_effect->setOffset(0, 0);
shadow_effect->setColor(Qt::black);
shadow_effect->setBlurRadius(10);
frame->setGraphicsEffect(shadow_effect);
//...
this->setAttribute(Qt::WA_TranslucentBackground);//特別注意這句
//如果發現沒有效果,那可能你設置了底層布局的問題。因為你可能設置了底層布局setContentsMargins的關系,如是,調整這個函數的參數即可
 
        

 

方法二。通過paintEvent()函數

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

//仍然要設置主窗體的背景透明

ps:這兩種方法,都需要注意兩點。其一是設置主窗體的背景透明this->setAttribute(Qt::WA_TranslucentBackground);其二是注意陰影的尺寸


免責聲明!

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



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