Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load a local html file into a QWebView in Python

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)

like image 973
Stef Avatar asked Apr 20 '16 08:04

Stef


1 Answers

Two observations:

  • path needs to be absolute (not relative)
  • use QUrl.fromLocalFile(path)

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_()
like image 158
Pawel Miech Avatar answered Nov 08 '22 00:11

Pawel Miech