使用样式表在 QMainWindow 上实现半透明背景

问题描述 投票:0回答:1

我想使用

QMainWindow::setStyleSheet
为我的 QMainWindow 设置半透明背景。

我做了类似的事情:

QMainWindow window;
window.setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
window.setStyleSheet("background-color: rgba(255, 0, 0, 128)");
window.setAttribute(Qt::WA_TranslucentBackground, true);
window.setFixedSize(800, 600);
window.show();

我得到了一个完全透明的窗口,我几乎看不到任何东西,如果我没有这样做:

window.setAttribute(Qt::WA_TranslucentBackground, true);

我得到一个全红的窗口。

我发现,继承 QMainWindow,重载

paintEvent()
并将
QPainter::fillRect()
与带有 alpha 的 QColor 一起使用,可以实现我想要的功能,但它没有使用样式表。

如何使用“setStyleSheet()”实现此目的?

c++ qt background transparent qtstylesheets
1个回答
4
投票

创建一个 QWidget,设置为 QMainWindow 上的中央小部件,并在此小部件上设置样式表,而不是主窗口。

QMainWindow window;
window.setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
window.setAttribute(Qt::WA_TranslucentBackground, true);
window.setFixedSize(800, 600);

QWidget widget(&window);
widget.setStyleSheet("background-color: rgba(255, 0, 0, 128)");

window.setCentralWidget(&widget);
window.show();
© www.soinside.com 2019 - 2024. All rights reserved.