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

}

};

相关推荐
G探险者11 小时前
LiteFlow 技术介绍
java·开发语言
FuckPatience13 小时前
Visual Studio C# 项目中文件后缀简介
开发语言·c#
014-code20 小时前
订单超时取消与库存回滚的完整实现(延迟任务 + 状态机)
java·开发语言
妙为20 小时前
银河麒麟V4下编译Qt5.12.12源码
c++·qt·国产化·osg3.6.5·osgearth3.2·银河麒麟v4
lly20240620 小时前
组合模式(Composite Pattern)
开发语言
游乐码20 小时前
c#泛型约束
开发语言·c#
Dontla20 小时前
go语言Windows安装教程(安装go安装Golang安装)(GOPATH、Go Modules)
开发语言·windows·golang
chushiyunen20 小时前
python rest请求、requests
开发语言·python
铁东博客20 小时前
Go实现周易大衍筮法三变取爻
开发语言·后端·golang
baidu_huihui20 小时前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip