Qt客户端技巧 -- 窗口美化 -- 窗口阴影
不解析,直接给示例
窗口设为不边框且背景透明,好用来承载阴影
窗口一个Widget用来作真实窗口的作用,在真实窗口上加上阴影特效
上下两层Widget方式
main.cpp
#include <QtCore/qglobal.h>
#if QT_VERSION >= 0x050000
#include <QtWidgets/QApplication>
#else
#include <QtGui/QApplication>
#endif#include "shadowwindow.h"int main(int argc, char *argv[])
{QApplication a(argc, argv);ShadowWindow wnd{};wnd.init();return a.exec();
}
shadowwindow.h
#ifndef SHADOWWINDOW_H
#define SHADOWWINDOW_H#include <QtCore/QObject>
#include <QtCore/qglobal.h>
#if QT_VERSION >= 0x050000
#include <QtWidgets/QWidget>
#else
#include <QtGui/QWidget>
#endif#include <QGraphicsDropShadowEffect>class ShadowWindow : public QWidget
{Q_OBJECT
public:explicit ShadowWindow(QWidget *parent = nullptr);virtual void init();protected:QWidget* realWnd;QGraphicsDropShadowEffect *shadowEffect;signals:
};#endif // SHADOWWINDOW_H
shadowwindow.cpp
#include "shadowwindow.h"ShadowWindow::ShadowWindow(QWidget *parent): QWidget{parent}, realWnd{new QWidget{this}},shadowEffect{new QGraphicsDropShadowEffect{this}} {/* setAttribute 与 setWindowFlag 最好在构造函数里面调用,不然出现未知错误 */this->setAttribute(Qt::WA_TranslucentBackground, true);this->setWindowFlag(Qt::FramelessWindowHint);this->resize(400, 300);this->show();
}void ShadowWindow::init() {const int pWidth = this->width();const int pHeight = this->height();const int shadowOffsetX = 5;const int shadowOffsetY = 5;realWnd->move(0, 0);realWnd->resize(pWidth - shadowOffsetX, pHeight - shadowOffsetY);realWnd->setStyleSheet("background-color:\"#aacc00\";");realWnd->show();shadowEffect->setOffset(shadowOffsetX, shadowOffsetY);shadowEffect->setBlurRadius(20);shadowEffect->setColor(QColor("#cccccc"));realWnd->setGraphicsEffect(shadowEffect);
}