不解析,直接給示例
窗口設為不邊框且背景透明,好用來承載陰影
窗口一個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);
}