1

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()```
Jaimee-lee Lincoln
  • 365
  • 1
  • 3
  • 11
  • 1
    You **must** use [`QUrl.fromLocalPath()`](https://doc.qt.io/qt-5/qurl.html#fromLocalFile), possibly with an absolute path (even if dynamically constructed). Note that if you don't need advanced and modern HTML features, consider using the more limited but quite smaller (in terms of memory and requirements) [QTextEdit](https://doc.qt.io/qt-5/qtextedit.html). – musicamante Feb 20 '23 at 08:36

2 Answers2

0

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()
Alexander
  • 16,091
  • 5
  • 13
  • 29
-1

In this article, you will know how to add or render HTML files in PyQt5 Dialog box python GUI. here is the reference, read it, it will help you.