Search code examples
pythonhtmlpyqt5qtwebengineqwebengineview

How to render HTML in PyQt5 window?


I'm new to using PyQt5 to create GUIs and I think I need a hand.

I'm trying to just create a simple window that renders a simple html file. However, when I use the code below the window renders, but the central widget/entire window is empty. Have I missed a step that allows the HTML to show?

Using the debugger mode in vscode, I've been able to work out that view.load()might successfully do something. It contains DrawChildren: 2, so I'm assuming that that might be my h1 and p elements.

What am I missing?

simple_test.html

<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>

</body>
</html>

python script

from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5 import QtWebEngineWidgets
import sys
import os

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Feelings App Prototype")
        
        view = QtWebEngineWidgets.QWebEngineView()
        view.load(QUrl('html_files\\simple_test.html'))

        self.setCentralWidget(view)

app = QApplication(sys.argv)


window = MainWindow()
window.show()


app.exec()```

Solution

  • For local html files you can read in the file and use the view's setHtml method.

    from PyQt5.QtWidgets import QApplication, QMainWindow
    from PyQt5 import QtWebEngineWidgets
    from pathlib import Path
    import sys
    import os
    
    class MainWindow(QMainWindow):
        def __init__(self):
            super().__init__()
    
            self.setWindowTitle("Feelings App Prototype")
            
            view = QtWebEngineWidgets.QWebEngineView()
            html = Path('html_files\\simple_test.html').read_text(encoding="utf8")
            view.setHtml(html)
            self.setCentralWidget(view)
    
    app = QApplication(sys.argv)
    
    
    window = MainWindow()
    window.show()
    
    
    app.exec()