Qt绘制阴影对话框

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

运行效果:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值