半透明弹窗需要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)); // 调整边框位置防止锯齿
}
};






![[特殊字符]《Qt实战:基于QCustomPlot的装药燃面动态曲线绘制(附右键菜单/样式美化/完整源码)》](https://i-blog.csdnimg.cn/direct/221b201d8c6049afa7fa8767fdb193f4.png)







![[免费]微信小程序宠物医院管理系统(uni-app+SpringBoot后端+Vue管理端)【论文+源码+SQL脚本】](https://i-blog.csdnimg.cn/direct/6e930f3dde3c4f2bb9cf4501c8642e1c.jpeg)


![Docker 使用镜像[SpringBoot之Docker实战系列] - 第537篇](https://i-blog.csdnimg.cn/img_convert/482e1f7c534731cfe0fbc734a8d94d58.png)

![Error in beforeDestroy hook: “Error: [ElementForm]unpected width “](https://i-blog.csdnimg.cn/direct/1727a2e78fc24efb89a3ecebcec3198a.png)