【问题标题】:QT QWebEngineView transparency for transparent html elements? [duplicate]QT QWebEngineView透明html元素的透明度? [复制]
【发布时间】:2022-01-02 15:24:31
【问题描述】:

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

我已经能够使窗口无框,并且已经能够使 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

【问题讨论】:

  • 可能需要为&lt;html&gt;central_widget设置透明度?

标签: python qt pyqt pyqt5 qwebengineview


【解决方案1】:

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

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

page = self.page()

page.setBackgroundColor(QtCore.Qt.transparent)

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

【讨论】:

  • 完美运行,谢谢!我自己无法将 C/C++ 代码完全翻译成 python。
猜你喜欢
  • 1970-01-01
  • 2014-02-12
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 2012-01-01
  • 1970-01-01
  • 2011-11-13
  • 2021-10-31
相关资源
最近更新 更多