简体   繁体   中英

Why my local html is not accessed when I load it into PySide6 QWebEngineView?

I was learning Qt6, and I wrote a demo putting a local html file into it to test the QWebEngineView Widget. However, the web page shows the info:

Your file counldn't be accessed
It may have been moved, edited, or deleted.
ERR_FILE_NOT_FOUND

Here is my test.py source code:

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())

In Addition, the docs.html has been put into the same directory as the test.py file. And when I print the web.fileDir , the result is correct.

In Qt in general is strongly preferred to use the qrc files, and the Qt resource management system. Here: Can QWebView load images from Qt resource files? is a small yet, neat example of something that is similar to your problem. You may also view the official PySide6 resource usage : https://doc.qt.io/qtforpython/tutorials/basictutorial/qrcfiles.html

You are hardcoded the url and the path may be wrong, in these cases the url is better step by step. I assume that the html is next to the .py then the solution is:

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM