首页 > 解决方案 > 为什么我的本地 html 加载到 PySide6 QWebEngineView 时无法访问?

问题描述

我正在学习 Qt6,我写了一个演示,将本地 html 文件放入其中以测试 QWebEngineView Widget。但是,网页显示信息:

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,结果是正确的。

标签: pythonpyside6

解决方案


一般来说Qt,强烈首选使用qrc文件和Qt资源管理系统。这里:QWebView 可以从 Qt 资源文件中加载图像吗? 是与您的问题类似的一个小而简洁的示例。您还可以查看官方PySide6资源使用情况: https ://doc.qt.io/qtforpython/tutorials/basictutorial/qrcfiles.html


推荐阅读