透明 html 元素的 QT QWebEngineView 透明度?

QT QWebEngineView transparency for transparent html elements?

我正在尝试使用 QWebEngine 在 PyQT5 中显示一些 html。问题是 html 的背景(正文)设置为 'transparent',但 QT 不会将其显示为透明。

我已经可以把window做成无边框的,也可以把QT加的html周围的白色部分做成透明的,但是网上找不到让 QT 将透明主体背景正确渲染为实际透明(而不是白色)的方法。

如果有人能提供帮助,我将不胜感激!

import os
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
from PyQt5.QtWebChannel import QWebChannel

my_html = """<!DOCTYPE html>
<html lang="en">
<head>
<style>
    body {
        background-color: transparent;
    }

    #square {
        width: 200px;
        height: 200px;
        background-color: red;
        position: absolute;
        top: 100px;
        left: 100px;
    }
</style>
</head>
<body>
    <div id="square"></div>
</body>
</html>
"""


class Browser(QtWebEngineWidgets.QWebEngineView):

    def __init__(self, html):
        super().__init__()

        self.url = QtCore.QUrl.fromLocalFile(os.getcwd() + os.path.sep)
        self.page().setHtml(html, baseUrl=self.url)


class Window(QtWidgets.QMainWindow):

    def __init__(self, html):
        super().__init__()
        self.html = html

        self.init_widgets()
        self.init_layout()
        self.setFixedSize(400, 400)

        # these make the border QT adds transparent, and removes the title bar
        # but doesn't affect the body background of the html which is set to transparent
        self.setStyleSheet("background: transparent; border: transparent;")
        self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.setAutoFillBackground(True)  # don't know what this does, as far as I know, nothing

    def init_widgets(self):
        self.browser = Browser(self.html)

    def init_layout(self):
        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.browser)

        central_widget = QtWidgets.QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)


def start():
    app = QtWidgets.QApplication(sys.argv)
    window = Window(my_html)
    window.show()
    app.exec_()


if __name__ == '__main__':
    start()

Picture for the result of the code above

我在 Qt 和 C/C++ 的旧问题中找到了答案: Transparent Background in QWebEnginePage

page 有默认背景 white,您必须更改它

page = self.page()

page.setBackgroundColor(QtCore.Qt.transparent)

page.setHtml(html, baseUrl=self.url)