问题
I am using PySide2.QtWebEngineWidgets.QWebEngineView() to setHtml on it to show a basic page like below.
This html file works fine in a browser because it has all the files in the same folder relative to the html file.
Once I setHtml to the below file, I get this exception:
Qt Error:
Uncaught ReferenceError: require is not defined
Is this related to Qt not finding the relative files unlike a regular browser? Or is there something else I should be doing? Or is QWebEngineView not advanced enough to execute javascript? If so what should I use?
I just want to create a webpage widget and load my Html like below. Everything else is done by the Html code.
To reproduce:
- Save the below html code as an html file
- Run this code:
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>
回答1:
(disclaimer: I'm not an expert in javascript)
The require command needs file system information so you can't use an HTML string but you need to create an HTML file and load it using 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
来源:https://stackoverflow.com/questions/64164738/how-to-embed-basic-html-page-using-qt