阴影边框很常见,诸如360以及其他很多软件都有类似效果,了解CSS3的同学们应该都知道box-shadow,它就是来设定阴影效果的,那么Qt呢?看过一些资料,说是QSS是基于CSS2的,既然如此,box-shadow是基于CSS3的!那么Qt定然就用不了!
搜了一些资料,每张图片都做成阴影效果的固然不可能,直接舍弃(即使可以,也不采纳)。如果实时的去画图,效率太低,最后选择了拼图的方式!
左上角、左下角、右上角、右下角、上、下、左、右,这几个方向都绘制对应的图即可!
#include "shadow_widget.h"ShadowWidget::ShadowWidget(QWidget *parent): QDialog(parent)
{setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);setAttribute(Qt::WA_TranslucentBackground);
}ShadowWidget::~ShadowWidget()
{}void ShadowWidget::paintEvent(QPaintEvent *event)
{QPainter painter(this);this->drawShadow(painter);painter.setPen(Qt::NoPen);painter.setBrush(Qt::white);painter.drawRect(QRect(SHADOW_WIDTH, SHADOW_WIDTH, this->width()-2*SHADOW_WIDTH, this->height()-2*SHADOW_WIDTH));
}void ShadowWidget::drawShadow(QPainter &painter)
{//绘制左上角、左下角、右上角、右下角、上、下、左、右边框QList pixmaps;pixmaps.append(QPixmap(":/shadow/shadow_left"));pixmaps.append(QPixmap(":/shadow/shadow_right"));pixmaps.append(QPixmap(":/shadow/shadow_top"));pixmaps.append(QPixmap(":/shadow/shadow_bottom"));pixmaps.append(QPixmap(":/shadow/shadow_left_top"));pixmaps.append(QPixmap(":/shadow/shadow_right_top"));pixmaps.append(QPixmap(":/shadow/shadow_left_bottom"));pixmaps.append(QPixmap(":/shadow/shadow_right_bottom"));painter.drawPixmap(0, 0, SHADOW_WIDTH, SHADOW_WIDTH, pixmaps[4]);painter.drawPixmap(this->width()-SHADOW_WIDTH, 0, SHADOW_WIDTH, SHADOW_WIDTH, pixmaps[5]);painter.drawPixmap(0,this->height()-SHADOW_WIDTH, SHADOW_WIDTH, SHADOW_WIDTH, pixmaps[6]);painter.drawPixmap(this->width()-SHADOW_WIDTH, this->height()-SHADOW_WIDTH, SHADOW_WIDTH, SHADOW_WIDTH, pixmaps[7]);painter.drawPixmap(0, SHADOW_WIDTH, SHADOW_WIDTH, this->height()-2*SHADOW_WIDTH, pixmaps[0].scaled(SHADOW_WIDTH, this->height()-2*SHADOW_WIDTH));painter.drawPixmap(this->width()-SHADOW_WIDTH, SHADOW_WIDTH, SHADOW_WIDTH, this->height()-2*SHADOW_WIDTH, pixmaps[1].scaled(SHADOW_WIDTH, this->height()- 2*SHADOW_WIDTH));painter.drawPixmap(SHADOW_WIDTH, 0, this->width()-2*SHADOW_WIDTH, SHADOW_WIDTH, pixmaps[2].scaled(this->width()-2*SHADOW_WIDTH, SHADOW_WIDTH));painter.drawPixmap(SHADOW_WIDTH, this->height()-SHADOW_WIDTH, this->width()-2*SHADOW_WIDTH, SHADOW_WIDTH, pixmaps[3].scaled(this->width()-2*SHADOW_WIDTH, SHADOW_WIDTH));
}
写一个公共的类,如果窗口要实现阴影效果直接继承就行了!SHADOW_WIDTH为阴影边框的像素,可以根据自己的需求自由调节!
也可使用QGraphicsDropShadowEffect来实现。。。