Search code examples
pythonpyside6

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.


Solution

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