QWebEngineView is a widget in PyQt6 that allows you to embed web content in your application. It is based on Chromium, an open-source web browser project, and provides a fast and secure browsing experience. In this tutorial, we will explore how to use the PyQt6 QWebEngineView widget, including creating a simple web browser, loading local and remote web pages, handling navigation events, and using JavaScript to interact with the web page.
Prerequisites
Before we start, make sure you have installed PyQt6 and PyQt6 WebEngine modules. You can install them using pip:
pip install PyQt6 PyQt6-WebEngine
Creating a Simple Web Browser in PyQt6 using QWebEngineView
Let’s start by creating a simple web browser that loads a specific web page. First, we need to import the necessary classes:
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout
from PyQt6.QtWebEngineWidgets import QWebEngineView
Next, we create a QApplication and a QWidget to hold the QWebEngineView widget:
app = QApplication([])
window = QWidget()
layout = QVBoxLayout()
Then, we create a QWebEngineView widget and add it to the layout:
view = QWebEngineView()
layout.addWidget(view)
Finally, we set the URL of the web page we want to load:
view.setUrl(QUrl("https://www.google.com/"))
Here is the complete code:
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout
from PyQt6.QtWebEngineWidgets import QWebEngineView
from PyQt6.QtCore import QUrl
app = QApplication([])
window = QWidget()
layout = QVBoxLayout()
view = QWebEngineView()
layout.addWidget(view)
view.setUrl(QUrl("https://www.google.com/"))
window.setLayout(layout)
window.show()
app.exec()
This code produces the following output, where we can see the google homepage loaded. We can now interact with this web-browser like we normally would.
Loading Local Web Pages using QWebEngineView
You can also use the QWebEngineView widget to load local web pages. For example, let’s say you have an HTML file named index.html
in the same directory as your Python script. You can load this file using the setHtml
method of the QWebEngineView widget.
view.setHtml(open("index.html").read())
If the file is located in some other folder than the Python file you are writing this code in, you will need to specify the full file path instead of just the name.
Handling Navigation Events
The QWebEngineView widget emits several signals when a navigation event occurs, such as when the user clicks a link or submits a form. You can connect to these signals to handle the events.
For example, the urlChanged
signal is emitted when the URL of the page changes. You can connect to this signal to update the address bar of your web browser:
def on_url_changed(url):
address_bar.setText(url.toString())
view.urlChanged.connect(on_url_changed)
The loadStarted
and loadFinished
signals are emitted when a page starts and finishes loading, respectively. You can use these signals to show a loading indicator:
def on_load_started():
loading_label.setText("Loading...")
def on_load_finished():
loading_label.setText("")
view.loadStarted.connect(on_load_started)
view.loadFinished.connect(on_load_finished)
Using JavaScript
The QWebEngineView widget also allows you to execute JavaScript code on the loaded web page using the runJavaScript
method. You can use this feature to interact with the web page and retrieve data.
For example, let’s say you want to get the title of the web page and display it in a label. You can use the following code:
def on_load_finished():
view.page().runJavaScript("document.title", lambda title: title_label.setText(title))
This code uses the runJavaScript
method to execute the JavaScript code document.title
, which retrieves the title of the web page. The result of the code is passed to a lambda function that sets the text of the title_label
widget.
You can also execute more complex JavaScript code, such as manipulating the DOM or calling web APIs. For example, let’s say you want to change the background color of the web page to red:
def on_load_finished():
view.page().runJavaScript("document.body.style.backgroundColor = 'red';")
This code uses the runJavaScript
method to execute the JavaScript code document.body.style.backgroundColor = 'red';
, which changes the background color of the web page to red.
Adding a Navigation and Searchbar
By default, the PyQt6 WebEngineView
widget does not show the search bar or navigation tools. If you want to add these features, you can do so by creating a toolbar widget and adding actions to it.
Here is an example of how to add a search bar and navigation tools to the PyQt QWebEngineView
widget:
from PyQt6.QtCore import QUrl
from PyQt6.QtGui import QKeySequence, QAction
from PyQt6.QtWidgets import QApplication, QMainWindow, QLineEdit, QToolBar
from PyQt6.QtWebEngineWidgets import QWebEngineView
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# Create a web view
self.web_view = QWebEngineView()
self.web_view.setUrl(QUrl("https://www.google.com/"))
self.setCentralWidget(self.web_view)
# Create a toolbar
toolbar = QToolBar()
self.addToolBar(toolbar)
# Add a back action to the toolbar
back_action = QAction("Back", self)
back_action.setShortcut(QKeySequence("Back"))
back_action.triggered.connect(self.web_view.back)
toolbar.addAction(back_action)
# Add a forward action to the toolbar
forward_action = QAction("Forward", self)
forward_action.setShortcut(QKeySequence("Forward"))
forward_action.triggered.connect(self.web_view.forward)
toolbar.addAction(forward_action)
# Add a reload action to the toolbar
reload_action = QAction("Reload", self)
reload_action.setShortcut(QKeySequence("Refresh"))
reload_action.triggered.connect(self.web_view.reload)
toolbar.addAction(reload_action)
# Add a search bar to the toolbar
self.search_bar = QLineEdit()
self.search_bar.returnPressed.connect(self.load_url)
toolbar.addWidget(self.search_bar)
def load_url(self):
url = self.search_bar.text()
if not url.startswith("http"):
url = "https://" + url
self.web_view.load(QUrl(url))
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
app.exec()
This marks the end of the PyQt6 QWebEngineView – Embedding a Web Browser Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.
I got this error:
Traceback (most recent call last):
File “c:\pythoncodes\DGA\Article1\from PyQt6.py”, line 1, in <module>
from PyQt6.QtWebEngineWidgets import QWebEngineView
ImportError: DLL load failed while importing QtWebEngineWidgets: The specified procedure could
When running this code:
from PyQt6.QtWebEngineWidgets import QWebEngineView
How can I solve this?