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)); // 调整边框位置防止锯齿

}

};

相关推荐
工程师0074 分钟前
C#接口的定义与使用
开发语言·c#·接口
sali-tec4 分钟前
C# 基于halcon的视觉工作流-章27-带色中线
开发语言·人工智能·算法·计算机视觉·c#
编的过程33 分钟前
vk框架或者普通函数封装的一些函数可以拿取使用【会持续更新】
开发语言·前端·javascript
sheepwjl39 分钟前
《嵌入式C语言笔记(十七):进制转换、结构体与位运算精要》
linux·c语言·开发语言·笔记·算法
源代码•宸1 小时前
深入浅出设计模式——创建型模式之单例模式 Singleton
开发语言·c++·经验分享·单例模式·设计模式
fsnine1 小时前
网络爬虫(python)入门
开发语言·爬虫·python
WilliamHu.1 小时前
金融分类提示词演示
开发语言·python·大模型·prompt
Shun_Tianyou2 小时前
Python Day17 面向对象 及例题分析
开发语言·数据结构·python·算法
wjs20242 小时前
XML 用途
开发语言
Dreamsi_zh2 小时前
Python爬虫07_Requests爬取图片
开发语言·爬虫·python