How to create a basic web browser in PyQt5?

In PyQt5, you can create a simple web browser using the QWebEngineView component. Here is a simple example code:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QToolBar, QLineEdit, QPushButton, QVBoxLayout, QWidget
from PyQt5.QtWebEngineWidgets import QWebEngineView

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

        self.browser = QWebEngineView()
        self.browser.setUrl("http://www.google.com")

        self.search_bar = QLineEdit()
        self.search_bar.returnPressed.connect(self.search)

        self.go_button = QPushButton("Go")
        self.go_button.clicked.connect(self.search)

        toolbar = QToolBar()
        toolbar.addWidget(self.search_bar)
        toolbar.addWidget(self.go_button)

        self.layout = QVBoxLayout()
        self.layout.addWidget(toolbar)
        self.layout.addWidget(self.browser)

        container = QWidget()
        container.setLayout(self.layout)
        self.setCentralWidget(container)

    def search(self):
        url = self.search_bar.text()
        if not url.startswith("http://") and not url.startswith("https://"):
            url = "http://" + url
        self.browser.setUrl(url)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    browser = SimpleBrowser()
    browser.show()
    sys.exit(app.exec_())

In this example, we have created a simple browser window with an address bar and a button where users can enter a website address in the address bar and load the webpage by clicking the button or pressing the Enter key.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds