Qt popup窗口半透明背景

半透明弹窗需要paintEvent()接口支持

**方法一:使用setStyleSheet设置半透明样式,**如果是子窗口,则可注释构建函数内属性设置

class TranslucentWidget : public QWidget {

public:

explicit TranslucentWidget(QWidget *parent = nullptr) : QWidget(parent) {

setObjectName("TranslucentWidget");

//只设置Qt::FramelessWindowHint和WA_TranslucentBackground,半透明背景默认会鼠标穿透,即使WA_TransparentForMouseEvents置为false也一样穿透;但追加设置Qt::Tool后,鼠标不穿透

setWindowFlags(Qt::FramelessWindowHint | Qt::Tool);

//必须设置这个属性,才能支持透明背景

setAttribute(Qt::WA_TranslucentBackground);

}

protected:

void paintEvent (QPaintEvent *event)

{

__super::paintEvent(event);

QStyleOption opt;

opt.init(this);

QPainter paint(this);

style()->drawPrimitive(QStyle::PE_Widget, &opt, &paint, this);

}

};

使用示例:

TranslucentWidget * floatWindow = new TranslucentWidget(this);

floatWindow ->setStyleSheet("QWidget#TranslucentWidget{background:rgba(100, 0, 0, 100);border:2px solid red;}");

floatWindow ->resize(QSize(500, 400));

floatWindow ->move(QPoint(0, 0));

floatWindow ->show();

floatWindow ->raise();

方法二:

class TranslucentWidget : public QWidget {

public:

explicit TranslucentWidget(QWidget *parent = nullptr) : QWidget(parent) {

setObjectName("TranslucentWidget");

//只设置Qt::FramelessWindowHint和WA_TranslucentBackground,半透明背景默认会鼠标穿透,即使WA_TransparentForMouseEvents置为false也一样穿透;但追加设置Qt::Tool后,鼠标不穿透

setWindowFlags(Qt::FramelessWindowHint | Qt::Tool);

// 必须设置这个属性,才能支持透明背景

setAttribute(Qt::WA_TranslucentBackground);

}

protected:

void paintEvent (QPaintEvent *) override {

QPainter painter(this);

painter.setRenderHint(QPainter::Antialiasing);

// 绘制一个半透明的红色背景

painter.fillRect(rect(), QColor(100, 0, 0, 100));

// 可选:绘制边框

painter.setPen(QPen(Qt::red, 2));

painter.drawRect(rect().adjusted(0, 0, -1, -1)); // 调整边框位置防止锯齿

}

};

相关推荐
玄同76523 分钟前
我的 Trae Skill 实践|使用 UV 工具一键搭建 Python 项目开发环境
开发语言·人工智能·python·langchain·uv·trae·vibe coding
Yorlen_Zhang33 分钟前
Python Tkinter Text 控件完全指南:从基础编辑器到富文本应用
开发语言·python·c#
lxl130734 分钟前
C++算法(1)双指针
开发语言·c++
不绝1911 小时前
C#进阶:预处理指令/反射,Gettype,Typeof/关键类
开发语言·c#
无小道1 小时前
Qt-qrc机制简单介绍
开发语言·qt
zhooyu1 小时前
C++和OpenGL手搓3D游戏编程(20160207进展和效果)
开发语言·c++·游戏·3d·opengl
HAPPY酷1 小时前
C++ 和 Python 的“容器”对决:从万金油到核武器
开发语言·c++·python
大鹏说大话1 小时前
告别 MSBuild 脚本混乱:用 C# 和 Nuke 构建清晰、可维护的现代化构建系统
开发语言·c#
Mr_sun.1 小时前
Day09——入退管理-入住-2
android·java·开发语言
MAGICIAN...2 小时前
【java-软件设计原则】
java·开发语言