【问题标题】:How to embed basic HTML page using Qt?如何使用 Qt 嵌入基本的 HTML 页面?
【发布时间】:2021-01-17 17:29:32
【问题描述】:

我正在使用 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>

【问题讨论】:

    标签: python html python-2.7 pyside2 qwebengineview


    【解决方案1】:

    (免责声明:我不是 javascript 专家)

    require 命令需要文件系统信息,因此您不能使用 HTML 字符串,但您需要创建一个 HTML 文件并使用 load() 加载它:

    import os
    
    from PySide2 import QtCore, QtWidgets, QtWebEngineWidgets
    
    
    CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
    
    
    if __name__ == "__main__":
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
        view = QtWebEngineWidgets.QWebEngineView()
    
        filename = os.path.join(CURRENT_DIR, "index.html")
        view.load(QtCore.QUrl.fromLocalFile(filename))
        view.show()
        sys.exit(app.exec_())
    
    ├── index.html
    ├── main.py
    └── monaco-editor
        ├── CHANGELOG.md
        ├── dev
        ├── esm
        ├── LICENSE
        ├── min
        ├── min-maps
        ├── monaco.d.ts
        ├── package.json
        ├── README.md
        └── ThirdPartyNotices.txt
    

    【讨论】:

    • 非常感谢它有效!我在您回复之前添加了简化代码,但现在效果很好。
    猜你喜欢
    • 1970-01-01
    • 2015-12-22
    • 2016-11-10
    • 2021-07-27
    • 1970-01-01
    • 2015-07-16
    • 2019-05-13
    • 2010-09-22
    相关资源
    最近更新 更多