阴影窗口的实现方法一般有三种,
方法一是:在窗口的构造函数中设置窗口的属性为:
setAttribute(Qt::WA_TranslucentBackground);
从而保证窗口不被绘制的部分透明化。接着重写绘制函数paintEvent(),
其代码示例如下:
void QT_Test::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
painter.setPen(color);
painter.drawPath(path);
}
}
方法二:用代用阴影的背景图片实现
QT的窗口对于一般的窗口程序来说,已经完全够用了。但有时候我们要求界面比较精美,或者还想自定义皮肤之类的话,就需要自己定义窗口。这里介绍一种简单的自定义窗口的方法。
自定义样式可以达到很多的自定义皮肤的效果,但自定义样式有时不能指定窗口的形状,或者实现窗口的阴影效果(使用QT的QGraphicsEffect定义阴影,但运行效率较低)。这样的话可以重载窗口的paintEvent函数实现自绘制窗口。
先准备一张有窗口阴影的背景图,然后在paintEvent函数里面使用QPainterx绘制这张图。
这里将窗口类命名为GraphicDialog
示例代码如下:
class GraphicDialog :
public QDialog
{
public:
GraphicDialog(QWidget*parent=NULL,Qt::WindowFlags
f = 0/* Qt::FramelessWindowHint*/);
~GraphicDialog(void);
protected:
void paintEvent(QPaintEvent *);
QPixmap background;
};
在窗口类构造函数中:
setWindowFlags(Qt::FramelessWindowHint); //无标题窗口
setAttribute(Qt::WA_TranslucentBackground);
background.load(":/Images/DialogBackground");
在paintEvent中
QPainter p(this);
p.drawPixmap(0, 0, rect().width(), rect().height(),
background);
方法三是通过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,调整这个函数的参数即可