首页 > 解决方案 > PyQt5 QWebEngine 对 Javascript 的错误渲染

问题描述

我正在使用 PyQt5 构建浏览器。这是一个相当大的代码,但这是我面临的主要问题。代码是这样的:

import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication, QMainWindow

app = QApplication(sys.argv)

web = QWebEngineView()
file = open("example.html", "r")
html = file.read()
web.setHtml(html)
file.close()
web.show()

sys.exit(app.exec_())

问题是渲染相当奇怪。渲染图在这里。 example.html 文件的内容:

<!DOCTYPE html>
<head><title>JS Example</title></head>
<h1>JS example</h1>
<p><button type = 'button' onclick = "document.getElementById('tobeshown').style.display='block'">Show hidden parts of this page</button></p>
<p id = 'tobeshown' style = "display:none">
Peekaboo!
</p>
<p>
<button type = 'button' onclick="document.getElementById('tobeshown').style.display='none'">Hide it!</button>
</p>
</body>
</html>

预期输出(这是在 Mozilla Firefox 浏览器中):这里

谁能告诉我为什么 PyQt5 渲染引擎会在顶部生成这些符号?我能做些什么来解决它?非常感谢。

标签: pythonpyqt5qwebengineview

解决方案


所以问题不在于 WebEngine 的渲染,而是 Python 对文件的读取。将文件的编码更改为 UTF-8 为我解决了这个问题。


推荐阅读