這個問題在這里已經有了答案: QWebEnginePage 中的透明背景 (2 個回答) 4 天前關閉。
我正在嘗試使用 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()
上面代碼的結果圖
uj5u.com熱心網友回復:
我在 Qt 和 C/C 的舊問題中找到了答案: QWebEnginePage 中的透明背景
page有默認背景white,你必須改變它
page = self.page()
page.setBackgroundColor(QtCore.Qt.transparent)
page.setHtml(html, baseUrl=self.url)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/368573.html
標籤:Python qt pyqt pyqt5 qwebengineview
上一篇:下面的if條件是什么意思?
下一篇:為什么qmake的路徑不同?
