Qt——功能:给窗口增加影子

测试环境:win10、Qt Creator 4.11.1、5.14.2版本SDK

 

1、平时使用软件时,经常看到弹出的窗口就像有了影子:设置窗口周围有一圈浅浅的灰色,就像窗口的投影。

       Qt——功能:给窗口增加影子_第1张图片

 

2、那么Qt中如何实现这种效果?

QGraphicsDropShadowEffect可以给QWidget的类增加投影效果,实际效果类似上图。

3、话不多说,上代码

WidgetDropShadow.h
#ifndef WIDGET_DROP_SHADOW_H
#define WIDGET_DROP_SHADOW_H

#include 
#include 
#include 
#include 

class WidgetDropShadow : public QWidget
{
    Q_OBJECT
public:
    explicit WidgetDropShadow(QWidget *parent = nullptr);
    ~WidgetDropShadow();

protected:
    void paintEvent(QPaintEvent *event) override;

private:
    QFrame* m_shadowFrame;
    QVBoxLayout* m_frameLayout;
    QGraphicsDropShadowEffect* m_shadowEffect;

private:
    void initWidget();
};

#endif // WIDGET_DROP_SHADOW_H


//////////////////////////////////////////////////////////////////////////////
WidgetDropShadow.c
#include "WidgetDropShadow.h"
#include 
#include 
#include 

WidgetDropShadow::WidgetDropShadow(QWidget *parent) : QWidget(parent),
    m_shadowEffect(nullptr)
{
    initWidget();
}

WidgetDropShadow::~WidgetDropShadow()
{

}

void WidgetDropShadow::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)

    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

void WidgetDropShadow::initWidget()
{
    setWindowFlags(Qt::FramelessWindowHint);

    m_shadowFrame = new QFrame();
    m_shadowFrame->setObjectName("shadowFrame");

    m_frameLayout = new QVBoxLayout();
    m_frameLayout->setContentsMargins(0,0,0,0);
    m_frameLayout->setSpacing(0);
    m_shadowFrame->setLayout(m_frameLayout);

    m_shadowEffect = new QGraphicsDropShadowEffect(this);
    m_shadowEffect->setBlurRadius(40);  //以像素为单位设置阴影
    m_shadowFrame->setStyleSheet("QFrame#shadowFrame{background:rgb(0,0,255);border-radius:8px;border:none;}");
    m_shadowEffect->setOffset(0, 0);    //设置阴影偏移方向
    m_shadowEffect->setColor(QColor(255,0,0));  //设置阴影颜色
    m_shadowFrame->setGraphicsEffect(m_shadowEffect);

    QHBoxLayout* layout = new QHBoxLayout();
    layout->setContentsMargins(18,18,18,18);
    layout->setSpacing(0);
    layout->addWidget(m_shadowFrame);

    setLayout(layout);
    setStyleSheet("background:rgb(255,255,255);border-radius:8px;border:1px solid rgb(230,230,230);");

    resize(600, 400);
}

运行效果:

 

Qt——功能:给窗口增加影子_第2张图片

修改参数:调整影子偏移方向:

m_shadowEffect->setOffset(0, 10);    //设置阴影偏移方向

效果如下:

Qt——功能:给窗口增加影子_第3张图片

 

你可能感兴趣的:(Qt)