5

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)

2
  • Have you tried with setUrl() instead of load() ? Commented Apr 20, 2016 at 8:46
  • Yes, I did. And it doesn't work either. Thank you Commented Apr 20, 2016 at 9:35

1 Answer 1

11

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_()
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your answer but it didn't work... when I print local_url, I got the right path to my file though BTW, I omit that I use PySide
is your file valid html? I'm not very familiar with pyside but in general it should work same. Have you tried printing your url? If you print url and click it in browser does it open all right? You should really post your full code that will help to reproduce problem (including imports), as you see there are different python qt wrappers, there are also different QT version and it may matter for your problem.
Yes i did write the URL directly in a web browser and it worked. Although, I don't think the other part of my code are the cause because the program wrked fine until 2 weeks ago. I think it may be the update on my machine (a raspberry Pi 2) which may be the cause of the disfunctioning.
hmm so this is important detail. Add all this to your question I'm sure someone should be able to help
This will probably not help OP, but to others who have stumbled on this the same as I did, this only works for me if the file I'm loading ends with .html suffix. Otherwise, it loads as a blank page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.