The QWebEngineView class in PyQt6 is a powerful widget for rendering and interacting with web content. It is part of the QtWebEngine module, which provides a Chromium-based web engine for displaying web pages in a PyQt6 application.
This tutorial provides a comprehensive guide to using QWebEngineView, from basic web rendering to advanced features such as JavaScript execution and custom URL handling.
1. Prerequisites
To use QWebEngineView, ensure that you have the PyQt6-WebEngine package installed. You can install it using pip:
pip install PyQt6-WebEngine
2. Basics of QWebEngineView
Key Features:
- Render web pages from URLs or HTML strings.
- Support for JavaScript and CSS.
- Interact with web pages via JavaScript.
- Handle custom navigation requests and events.
Importing QWebEngineView
from PyQt6.QtWebEngineWidgets import QWebEngineView from PyQt6.QtWebEngineCore import QWebEnginePage, QWebEngineProfile from PyQt6.QtWidgets import QApplication, QMainWindow
3. Example 1: Displaying a Web Page
This example demonstrates how to load and display a web page using QWebEngineView.
Code:
import sys from PyQt6.QtWidgets import QApplication, QMainWindow from PyQt6.QtWebEngineWidgets import QWebEngineView class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Basic Web Browser") self.resize(800, 600) # Create a QWebEngineView instance self.browser = QWebEngineView() # Load a URL self.browser.setUrl("https://www.google.com") # Set the QWebEngineView as the central widget self.setCentralWidget(self.browser) app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec())
4. Example 2: Loading HTML Content
You can load raw HTML content into the QWebEngineView using the setHtml method.
Code:
import sys from PyQt6.QtWidgets import QApplication, QMainWindow from PyQt6.QtWebEngineWidgets import QWebEngineView class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Load HTML Content") self.resize(800, 600) self.browser = QWebEngineView() # Load HTML content html_content = """ <!DOCTYPE html> <html> <head> <title>PyQt6 WebEngine</title> </head> <body> <h1>Welcome to PyQt6 WebEngine!</h1> <p>This is a simple example of loading HTML content.</p> </body> </html> """ self.browser.setHtml(html_content) self.setCentralWidget(self.browser) app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec())
5. Example 3: Handling Navigation
You can handle navigation events by connecting to the urlChanged signal.
Code:
import sys from PyQt6.QtWidgets import QApplication, QMainWindow from PyQt6.QtWebEngineWidgets import QWebEngineView class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Handle Navigation") self.resize(800, 600) self.browser = QWebEngineView() self.browser.setUrl("https://www.example.com") # Connect to the URL change signal self.browser.urlChanged.connect(self.on_url_changed) self.setCentralWidget(self.browser) def on_url_changed(self, url): print(f"Navigated to: {url.toString()}") app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec())
6. Example 4: Executing JavaScript
You can execute JavaScript code on the loaded web page using the runJavaScript method.
Code:
import sys from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget from PyQt6.QtWebEngineWidgets import QWebEngineView class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Execute JavaScript") self.resize(800, 600) self.browser = QWebEngineView() self.browser.setUrl("https://www.example.com") # Button to execute JavaScript self.button = QPushButton("Get Page Title") self.button.clicked.connect(self.execute_js) layout = QVBoxLayout() layout.addWidget(self.browser) layout.addWidget(self.button) container = QWidget() container.setLayout(layout) self.setCentralWidget(container) def execute_js(self): # Run JavaScript to get the page title self.browser.page().runJavaScript("document.title", self.js_callback) def js_callback(self, result): print(f"Page title: {result}") app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec())
7. Example 5: Customizing Web Page Settings
You can customize settings like enabling/disabling JavaScript or plugins using the QWebEngineSettings class.
Code:
import sys from PyQt6.QtWidgets import QApplication, QMainWindow from PyQt6.QtWebEngineWidgets import QWebEngineView class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Custom Page Settings") self.resize(800, 600) self.browser = QWebEngineView() self.browser.setUrl("https://www.google.com") # Access the settings and customize them settings = self.browser.settings() settings.setAttribute(settings.WebAttribute.JavascriptEnabled, True) settings.setAttribute(settings.WebAttribute.PluginsEnabled, False) self.setCentralWidget(self.browser) app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec())
8. Example 6: Downloading Files
You can handle file downloads by implementing a custom download handler.
Code:
import sys from PyQt6.QtWidgets import QApplication, QMainWindow, QFileDialog from PyQt6.QtWebEngineWidgets import QWebEngineView, QWebEngineProfile class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Handle Downloads") self.resize(800, 600) self.browser = QWebEngineView() self.browser.setUrl("https://www.example.com") # Set up download handler profile = self.browser.page().profile() profile.downloadRequested.connect(self.on_download_requested) self.setCentralWidget(self.browser) def on_download_requested(self, download): # Prompt user to select a save location save_path, _ = QFileDialog.getSaveFileName(self, "Save File", download.path()) if save_path: download.setPath(save_path) download.accept() app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec())
Summary of Features:
- Display Web Content: Load web pages from URLs or HTML strings.
- Handle Events: React to navigation changes and user interactions.
- JavaScript Integration: Execute and retrieve results from JavaScript code.
- Custom Page Settings: Enable or disable JavaScript, plugins, and other features.
- File Downloads: Handle file downloads with custom save locations.
These examples demonstrate how to use QWebEngineView to integrate web content into PyQt6 applications, providing a wide range of functionality for creating web-enabled desktop applications.