猿问

如何使用Qt嵌入基本的HTML页面?

我正在使用 PySide2.QtWebEngineWidgets.QWebEngineView() 在其上设置 Html 以显示如下所示的基本页面。

该 html 文件在浏览器中工作正常,因为它的所有文件都位于与 html 文件相关的同一文件夹中。

将 Html 设置为以下文件后,我收到此异常:

Qt 错误:

Uncaught ReferenceError: require is not defined

这是否与 Qt 不像常规浏览器那样找不到相关文件有关?或者还有什么我应该做的吗?或者 QWebEngineView 不够先进,无法执行 javascript?如果是这样我应该使用什么?

我只想创建一个网页小部件并加载我的 Html,如下所示。其他一切都是由 Html 代码完成的。

重现:

  1. 将以下 html 代码另存为 html 文件

  2. 运行这段代码:

from PySide2 import QtCore, QtWidgets, QtGui

from PySide2.QtWebEngineWidgets import QWebEngineView


editor = QWebEngineView()

htmlfile = 'C:/myHtmlFile.html'

with open(htmlfile, 'r') as f:

    html = f.read()

    editor.setHtml(html)

    

editor.show()

<!DOCTYPE html>

<html>

<head>

    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >

</head>

<body>


<div id="container" style="width:800px;height:600px;border:1px solid grey"></div>


<script src="monaco-editor/min/vs/loader.js"></script>

<script>

    require.config({ paths: { 'vs': 'monaco-editor/min/vs' }});

    require(['vs/editor/editor.main'], function() {

        var editor = monaco.editor.create(document.getElementById('container'), {

            value: [

                'function x() {',

                '\tconsole.log("Hello world!");',

                '}'

            ].join('\n'),

            language: 'javascript',

            fontFamily:"Verdana",

            theme: "vs-dark"

        });

    });

</script>

</body>

</html>


慕慕森
浏览 468回答 1
1回答

慕丝7291255

require 命令需要文件系统信息,因此您不能使用 HTML 字符串,但您需要创建一个 HTML 文件并使用 load() 加载它:import osfrom PySide2 import QtCore, QtWidgets, QtWebEngineWidgetsCURRENT_DIR = os.path.dirname(os.path.realpath(__file__))if __name__ == "__main__":&nbsp; &nbsp; import sys&nbsp; &nbsp; app = QtWidgets.QApplication(sys.argv)&nbsp; &nbsp; view = QtWebEngineWidgets.QWebEngineView()&nbsp; &nbsp; filename = os.path.join(CURRENT_DIR, "index.html")&nbsp; &nbsp; view.load(QtCore.QUrl.fromLocalFile(filename))&nbsp; &nbsp; view.show()&nbsp; &nbsp; sys.exit(app.exec_())├── index.html├── main.py└── monaco-editor&nbsp; &nbsp; ├── CHANGELOG.md&nbsp; &nbsp; ├── dev&nbsp; &nbsp; ├── esm&nbsp; &nbsp; ├── LICENSE&nbsp; &nbsp; ├── min&nbsp; &nbsp; ├── min-maps&nbsp; &nbsp; ├── monaco.d.ts&nbsp; &nbsp; ├── package.json&nbsp; &nbsp; ├── README.md&nbsp; &nbsp; └── ThirdPartyNotices.txt
随时随地看视频慕课网APP

相关分类

Python
我要回答