Load a local html file into a QWebView in Python
Asked Answered
H

1

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)

Heathenism answered 20/4, 2016 at 8:37 Comment(2)
Have you tried with setUrl() instead of load() ?Electrocautery
Yes, I did. And it doesn't work either. Thank youHeathenism
S
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_()
Sociopath answered 20/4, 2016 at 8:48 Comment(5)
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 PySideHeathenism
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.Sociopath
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.Heathenism
hmm so this is important detail. Add all this to your question I'm sure someone should be able to helpSociopath
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.Protective

© 2022 - 2024 — McMap. All rights reserved.