So far we've learned the basics of building Python GUI applications with Qt. In this tutorial we'll take what we've learned and apply it to creating a custom web browser — Mozzerella Ashbadger — in Python using PyQt5.
Mozzerella Ashbadger is the latest revolution in web browsing! Go back and forward! Save files! Get help! (you'll need it). Any similarity to other browsers is entirely coincidental.
QtWebEngineWidgets is not included in the main PyQt5 repository. If you see errors when running this relating to this module, you can install it using pip install PyQtWebEngine
The full source code for MooseAche is available in the 15 minute apps repository. You can download/clone to get a working copy, then install requirements using:
pip3 install -r requirements.txt
You can then run MooseAche with:
python3 browser.py
Read on for a walkthrough of how the code works.
The browser widget: QWebEngineView
The core of our Python web browser is QWebEngineView, which we import from PyQt5.QtWebEngineWidgets. This provides a complete browser widget that handles the rendering of downloaded web pages. It's the essential building block for any PyQt5 web browser project.
Below is the bare-minimum of code required to use the QWebEngineView web browser widget in PyQt5.
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import *
import sys
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.browser = QWebEngineView()
self.browser.setUrl(QUrl("http://www.google.com"))
self.setCentralWidget(self.browser)
self.show()
app = QApplication(sys.argv)
window = MainWindow()
app.exec_()
If you click around a bit you'll discover that the browser behaves as expected — links work correctly, and you can interact with the pages. However, you'll also notice things you take for granted are missing — like an URL bar, controls or any sort of interface whatsoever. This makes it a little tricky to use.
Next steps: Adding navigation controls
In the next part we'll extend this basic skeleton of a Python web browser and add navigation controls including back, forward, reload buttons, and an address bar. These are the features that transform a simple QWebEngineView widget into a fully functional web browser application built with PyQt5.
Create GUI Applications with Python & Qt6 by Martin Fitzpatrick
(PySide6 Edition) The hands-on guide to making apps with Python — Over 15,000 copies sold!