Load a local html file into a QWebView in Python

Stef picture Stef · Apr 20, 2016 · Viewed 8.1k times · Source

Here's my problem: I want to load a local html file into a QWebView in Python. EDIT: I use PySide as a Qt package.

My code:

class myWindow(QWidget):
    def __init__(self, parent=None):
        self.view = QWebView(self)
        filepath = "file://" + os.path.join(os.path.dirname(__file__), 'googlemap.html')
        self.view.load(QUrl(filepath))

This is just showing me a blank widget. If I change

self.view.load(QUrl(filepath)

by

self.view.load(QUrl("http://www.google.com/"))

It works fine.

However, the file is clearly in the good directory and I can open the same file directly with my browser.

EDIT 2: The problem appears after an update on my Raspberry Pi 2 (which runs the code above)

Answer

Pawel Miech picture Pawel Miech · Apr 20, 2016

Two observations:

so something like this

file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "aa.html"))
local_url = QUrl.fromLocalFile(file_path)
browser.load(local_url)

should work.

Full example:

from PyQt4.QtWebKit import QWebView
from PyQt4.QtGui import QApplication
from PyQt4.QtCore import QUrl
import sys
import os

app = QApplication(sys.argv)

browser = QWebView()
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "aa.html"))
local_url = QUrl.fromLocalFile(file_path)
browser.load(local_url)

browser.show()

app.exec_()