我正在学习Qt6,我写了一个演示,将一个本地html文件放入其中以测试QWebEngineView小部件。但是,该网页会显示以下信息:
Your file counldn't be accessed
It may have been moved, edited, or deleted.
ERR_FILE_NOT_FOUND
以下是我的test.py
源代码:
import sys
from PySide6.QtWidgets import (QApplication, QWidget, QVBoxLayout)
from PySide6 import QtCore
from PySide6.QtWebEngineWidgets import QWebEngineView
class webView(QWidget):
def __init__(self):
super(webView, self).__init__()
self.layout = QVBoxLayout(self)
self.webV = QWebEngineView()
self.fileDir = QtCore.QFileInfo("./docs.html").absoluteFilePath()
print(self.fileDir)
self.webV.load(QtCore.QUrl("file:///" + self.fileDir))
self.layout.addWidget(self.webV)
if __name__ == "__main__":
app = QApplication([])
web = webView()
web.show()
sys.exit(app.exec())
此外,已将docs.html
放入与test.py
文件相同的目录中。当我打印web.fileDir
时,结果是正确的。
发布于 2021-10-31 16:34:50
你是硬编码的网址和路径可能是错误的,在这些情况下,网址是更好的一步。我假设html紧挨着.py,那么解决方案是:
import os
from pathlib import Path
import sys
from PySide6.QtCore import QUrl
from PySide6.QtWidgets import QApplication, QVBoxLayout, QWidget
from PySide6.QtWebEngineWidgets import QWebEngineView
CURRENT_DIRECTORY = Path(__file__).resolve().parent
class webView(QWidget):
def __init__(self):
super(webView, self).__init__()
filename = os.fspath(CURRENT_DIRECTORY / "docs.html")
url = QUrl.fromLocalFile(filename)
self.webV = QWebEngineView()
self.webV.load(url)
layout = QVBoxLayout(self)
layout.addWidget(self.webV)
if __name__ == "__main__":
app = QApplication([])
web = webView()
web.show()
sys.exit(app.exec())
发布于 2021-10-31 12:45:09
在Qt
中一般强烈建议使用qrc
文件,并使用Qt
资源管理系统。这里:Can QWebView load images from Qt resource files?是一个与你的问题相似的小而整洁的例子。您还可以查看官方的PySide6
资源使用情况:https://doc.qt.io/qtforpython/tutorials/basictutorial/qrcfiles.html
https://stackoverflow.com/questions/69786515
复制相似问题