在Qt的开发过程中,经常会遇到各种提示弹框,比如删除提示,异常错误提示,操作步骤等对话框,而且都是模态的,如果没有阴影比较生硬,添加阴影看起来比较有突兀感,本篇介绍Qt的阴影对话框绘制。
1.通常我们会使用Qt自带的QGraphicsDropShadowEffect来产生阴影效果,但这个类对QDialog没有效果。
例如:
QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect(this);
shadow->setOffset(0, 0);
shadow->setColor(QColor("#333333"));
shadow->setBlurRadius(10);
this->setGraphicsEffect(shadow);
setStyleSheet(QString::fromUtf8("QDialog{background-color:#FFFFFF;border-radius:5px;margin:10px 10px 10px 10px;}"));
这样写其实没有效果,那么我们可以采用绘制的方式。
2.paintEvent绘制阴影
重写paintEvent事件
#ifndef FRAMELESSDIALOG_H
#define FRAMELESSDIALOG_H
#include <QDialog>
class FramelessDialog: public QDialog
{
public:
FramelessDialog(QWidget *parent = nullptr);
protected:
virtual void paintEvent(QPaintEvent *event) override;
};
#endif // FRAMELESSDIALOG_H
#include "framelessdialog.h"
#include <QPainter>
#include <QPainterPath>
#include <QGraphicsDropShadowEffect>
#include <QtMath>
FramelessDialog::FramelessDialog(QWidget *parent) : QDialog(parent)
{
//隐藏原生态的标题栏
this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowMinimizeButtonHint | Qt::Tool);
setAttribute(Qt::WA_TranslucentBackground, true);
// QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect(this);
// shadow->setOffset(0, 0);
// shadow->setColor(QColor("#333333"));
// shadow->setBlurRadius(10);
// this->setGraphicsEffect(shadow);
// setStyleSheet(QString::fromUtf8("QDialog{background-color:#FFFFFF;border-radius:5px;margin:10px 10px 10px 10px;}"));
}
void FramelessDialog::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainterPath path;
path.setFillRule(Qt::WindingFill);
path.addRoundedRect(5, 5, this->width() - 5 * 2, this->height() - 5 * 2, 3, 3);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.fillPath(path, QBrush(Qt::white));
QColor color(Qt::gray);
for (int i = 0; i < 5; i++)
{
QPainterPath path;
path.setFillRule(Qt::WindingFill);
path.addRoundedRect(5 - i, 5 - i, this->width() - (5 - i) * 2, this->height() - (5 - i) * 2, 3 + i, 3 + i);
color.setAlpha(80 - qSqrt(i) * 40);
painter.setPen(color);
painter.drawPath(path);
}
}
调用:
void QGraphicsDropShadowEffectDemo::slotShowDialog2()
{
FramelessDialog *dialog = new FramelessDialog();
dialog->exec();
}
运行效果: