【发布时间】: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()
【问题讨论】:
-
可能需要为
<html>或central_widget设置透明度?
标签: python qt pyqt pyqt5 qwebengineview