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

}

};

相关推荐
froginwe111 分钟前
R 矩阵:解析与应用
开发语言
_OP_CHEN5 分钟前
C++基础:(十六)priority_queue和deque的深度解析
开发语言·c++
C++ 老炮儿的技术栈10 分钟前
include″″与includ<>的区别
c语言·开发语言·c++·算法·visual studio
Vallelonga10 分钟前
Rust 设计模式 Marker Trait + Blanket Implementation
开发语言·设计模式·rust
CHANG_THE_WORLD17 分钟前
PDFium导出pdf 图像
开发语言·c++·pdf
Larry_Yanan20 分钟前
QML学习笔记(四十三)QML与C++交互:上下文属性暴露
c++·笔记·qt·学习·ui·交互
owCode30 分钟前
4-C++智能指针
开发语言·c++
liu****40 分钟前
10.queue的模拟实现
开发语言·数据结构·c++·算法
哦你看看1 小时前
学习Python 03
开发语言·windows·python
小龙报1 小时前
《彻底理解C语言指针全攻略(6)-- qsort、sizeof和strlen》
c语言·开发语言·职场和发展·创业创新·学习方法·业界资讯·visual studio