Issue
I am trying to display some html in PyQT5 with QWebEngine. The problem is that the background (body) of the html is set to 'transparent', but QT won't display it as transparent.
I have been able to make the window frameless, and have been able to make the white part around the html that QT adds transparent, but no where on the internet can I find a way to have QT correctly render the transparent body background as actually transparent (instead of white).
If anyone can help, I would really appreciate it!
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
Solution
I found answer in old question for Qt and C/C++: Transparent Background in QWebEnginePage
page
has default background white
and you have to change it
page = self.page()
page.setBackgroundColor(QtCore.Qt.transparent)
page.setHtml(html, baseUrl=self.url)
Answered By - furas
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.