If you are using setHtml()
then as indicated by the docs the external resources will be relative to the url that you pass as second parameters:
void QWebEngineView::setHtml(const QString &html, const QUrl &baseUrl = QUrl())
[...]
External objects, such as stylesheets or images referenced in the HTML document, are located relative to baseUrl.
[...]
So in your case the solution is:
import os
from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets
if __name__ == "__main__":
import sys
sys.argv.append("--disable-web-security")
app = QtWidgets.QApplication(sys.argv)
wnd = QtWidgets.QWidget()
genVLayout = QtWidgets.QVBoxLayout(wnd)
verticalLayout_7 = QtWidgets.QVBoxLayout()
webEngineViewGen = QtWebEngineWidgets.QWebEngineView(wnd)
webEngineViewGen.setUrl(QtCore.QUrl("about:blank"))
with open('main.html','r') as fh:
html = fh.read()
current_dir = os.path.dirname(os.path.abspath(__file__))
url = QtCore.QUrl.fromLocalFile(os.path.join(current_dir, "main.html"))
webEngineViewGen.setHtml(html, url)
verticalLayout_7.addWidget(webEngineViewGen)
genVLayout.addLayout(verticalLayout_7)
wnd.show()
sys.exit(app.exec_())
Or simply use the load()
method:
import os
from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets
if __name__ == "__main__":
import sys
sys.argv.append("--disable-web-security")
app = QtWidgets.QApplication(sys.argv)
wnd = QtWidgets.QWidget()
genVLayout = QtWidgets.QVBoxLayout(wnd)
verticalLayout_7 = QtWidgets.QVBoxLayout()
webEngineViewGen = QtWebEngineWidgets.QWebEngineView(wnd)
webEngineViewGen.setUrl(QtCore.QUrl("about:blank"))
current_dir = os.path.dirname(os.path.abspath(__file__))
url = QtCore.QUrl.fromLocalFile(os.path.join(current_dir, "main.html"))
webEngineViewGen.load(url)
verticalLayout_7.addWidget(webEngineViewGen)
genVLayout.addLayout(verticalLayout_7)
wnd.show()
sys.exit(app.exec_())
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…