Creating a Tabbed Browser using PyQt5


What is PyQt5 Library in Python?

A Python binding for the well-known cross-platform GUI toolkit Qt is called PyQt5. It enables Python programmers to construct desktop programmes that can run on Windows, macOS, and Linux and have a sophisticated graphical user interface (GUI). PyQt5 gives users access to all of Qt's features, including as support for cutting-edge graphics, animations, and multimedia.

What are the Advantages and Disadvantages of PyQt5 Library?

Advantages

  • Cross-platform functionality − PyQt5 programmes may operate on several systems without the need for code modifications. This enables developers to produce software that is usable by a variety of consumers independent of operating system.

  • Comprehensive collection of widgets and tools − PyQt5 offers a large selection of widgets and tools that may be used to build intricate user interfaces with plenty of features. They consist of many different elements, such as buttons, labels, text boxes, combo boxes, list boxes, progress bars, sliders, and spin boxes.

  • Simple Python integration − PyQt5 enables programmers to build desktop apps with all of Python's capabilities. This includes the capacity to enhance the functionality of their programmes using Python libraries and modules.

  • Modifiable appearance and feel − PyQt5 enables programmers to modify the appearance and feel of their applications, including the usage of unique icons, fonts, and stylesheets. Applications may thus be customised to meet the demands of their users and to coordinate with their company's identity thanks to this.

Disadvantages

  • A steep learning curve − PyQt5 may be difficult to master for those new to GUI development, particularly those unfamiliar with Qt. This may make it difficult for developers to design complicated apps that make advantage of the whole Qt feature set.

  • Licensing payments − Since Qt is a commercial product, developers who utilise PyQt5 in their projects may have to pay licence fees. Nevertheless, there are free open-source and community copies of Qt available.

  • Performance concerns − Performance difficulties may occur with PyQt5 applications, particularly when working with huge volumes of data or complicated visuals. This might make it difficult to design speedy and responsive apps, particularly on older hardware.

  • Issues with compatibility − PyQt5 programmes may not be entirely compatible with all operating systems and Python versions. This may make creating apps that perform flawlessly across several platforms and settings challenging.

Steps and Processes

Let's start by writing the code for our tabbed browser. We will break down the code into smaller chunks and explain each part in detail.

Creating a tabbed browser using PyQt5 can be a useful project for those who want to learn about GUI programming in Python. In this tutorial, we will go through the steps of building a basic tabbed browser using PyQt5.

Step 1 − Install PyQt5

If you don't have PyQt5 installed, you can install it using pip. Open your command prompt or terminal and type the following command −

pip install PyQt5

Step 2 − Import the Necessary Modules

Open your text editor and create a new Python file. Import the necessary modules −

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *

The first two lines import the core and widgets classes from PyQt5, while the third line imports the web engine widgets that we will use for displaying web pages.

Step 3 − Create the main Window

Create a new class for the main window that inherits from QMainWindow. Inside the class, create a QTabWidget and set it as the central widget of the main window. This will be the area where we display the tabs −

class MainWindow(QMainWindow):
   def __init__(self):
      super(MainWindow, self).__init__()

      self.tabs = QTabWidget()
      self.setCentralWidget(self.tabs)

Step 4 − Create a new tab

Inside the main window class, create a method for adding a new tab. This method will be called whenever the user wants to open a new tab. Inside the method, create a new QWidget and a QWebEngineView. The QWidget will be the container for the web engine view. Set the QWidget as the tab and set the QWebEngineView as its layout −

class MainWindow(QMainWindow):
   def __init__(self):
      super(MainWindow, self).__init__()

      self.tabs = QTabWidget()
      self.setCentralWidget(self.tabs)

   def add_new_tab(self, qurl=None):
      if qurl is None:
         qurl = QUrl('https://www.google.com')

      browser = QWebEngineView()
      browser.setUrl(qurl)

      i = self.tabs.addTab(browser, "New Tab")
      self.tabs.setCurrentIndex(i)

The method takes a qurl argument, which is the URL of the page to load. If no URL is provided, it defaults to Google's homepage. The method creates a new QWebEngineView and sets its URL to the provided URL. Then it adds the QWebEngineView to the tab widget and sets the tab title to "New Tab". Finally, it sets the current tab to the newly created tab.

Step 5 − Connect the tab bar to the add_new_tab Method

When the user clicks on the "+" button in the tab bar, we want to add a new tab. To do this, we need to connect the "+" button to the add_new_tab method. Inside the MainWindow class, add the following code −

self.tabs.tabBar().setContextMenuPolicy(Qt.PreventContextMenu)
self.tabs.tabBar().setTabsClosable(True)
self.tabs.tabBar().tabCloseRequested.connect(lambda index: self.tabs.removeTab(index))
self.tabs.tabBar().addTab("+")
self.tabs.tabBar().tabBarClicked.connect(self.tab_bar_clicked)

The first line sets the context menu policy to PreventContextMenu. The second line makes the tabs closable. The third line connects the tabCloseRequested signal to a lambda function that removes the tab when the close button is clicked. The fourth line adds a "+" tab. Finally, the fifth line connects the tabBarClicked signal to a method that checks whether the "+" tab was clicked, and if so, calls the add_new_tab method −

def tab_bar_clicked(self, index):
   if index == self.tabs.count() - 1:
      self.add_new_tab()

This method checks whether the index of the clicked tab is the index of the "+" tab. If it is, it calls the add_new_tab method.

Step 6 − Add a Navigation bar

We will now add a navigation bar that will allow the user to navigate to different web pages. Inside the MainWindow class, add the following code.

self.navbar = QToolBar("Navigation")
self.addToolBar(self.navbar)

self.back_btn = QAction("Back", self)
self.back_btn.triggered.connect(lambda: self.tabs.currentWidget().back())
self.navbar.addAction(self.back_btn)

self.forward_btn = QAction("Forward", self)
self.forward_btn.triggered.connect(lambda: self.tabs.currentWidget().forward())
self.navbar.addAction(self.forward_btn)

self.reload_btn = QAction("Reload", self)
self.reload_btn.triggered.connect(lambda: self.tabs.currentWidget().reload())
self.navbar.addAction(self.reload_btn)

self.urlbar = QLineEdit()
self.urlbar.returnPressed.connect(self.navigate)
self.navbar.addWidget(self.urlbar)

This code creates a new toolbar and adds it to the main window. It also creates three buttons for going back, going forward, and reloading the page. The buttons are connected to their respective methods of the current tab. Finally, it creates a QLineEdit for entering URLs and connects its returnPressed signal to a navigate method.

Step 7 − Implement the Navigate Method

The navigate method will be called when the user presses the Enter key in the URL bar. It will load the URL entered by the user in the current tab. Add the following code to the MainWindow class −

def navigate(self):
   qurl = QUrl(self.urlbar.text())
   if qurl.scheme() == "":
      qurl.setScheme("http")
   self.tabs.currentWidget().setUrl(qurl)

This method creates a QUrl object from the text entered in the URL bar. If the URL doesn't have a scheme (i.e. "http://" or "https://"), it adds "http://" as the default scheme. Finally, it sets the URL of the current tab to the entered URL.

Step 8 − Run the Application

To run the application, create an instance of the MainWindow class and call its show method −

app = QApplication([])
window = MainWindow()
window.show()
app.exec_()

This code creates a new QApplication instance, creates a new MainWindow instance, and shows the main window. Finally, it starts the main event loop using the exec_ method of the QApplication instance.

Example

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *

class MainWindow(QMainWindow):
   def __init__(self):
      super(MainWindow, self).__init__()

      self.tabs = QTabWidget()
      self.setCentralWidget(self.tabs)

class MainWindow(QMainWindow):
   def __init__(self):
      super(MainWindow, self).__init__()

      self.tabs = QTabWidget()
      self.setCentralWidget(self.tabs)

   def add_new_tab(self, qurl=None):
      if qurl is None:
         qurl = QUrl('https://www.google.com')

      browser = QWebEngineView()
      browser.setUrl(qurl)

      i = self.tabs.addTab(browser, "New Tab")
      self.tabs.setCurrentIndex(i)

self.tabs.tabBar().setContextMenuPolicy(Qt.PreventContextMenu)
self.tabs.tabBar().setTabsClosable(True)
self.tabs.tabBar().tabCloseRequested.connect(lambda index: self.tabs.removeTab(index))
self.tabs.tabBar().addTab("+")
self.tabs.tabBar().tabBarClicked.connect(self.tab_bar_clicked)

def tab_bar_clicked(self, index):
   if index == self.tabs.count() - 1:
      self.add_new_tab()

self.navbar = QToolBar("Navigation")
self.addToolBar(self.navbar)

self.back_btn = QAction("Back", self)
self.back_btn.triggered.connect(lambda: self.tabs.currentWidget().back())
self.navbar.addAction(self.back_btn)

self.forward_btn = QAction("Forward", self)
self.forward_btn.triggered.connect(lambda: self.tabs.currentWidget().forward())
self.navbar.addAction(self.forward_btn)

self.reload_btn = QAction("Reload", self)
self.reload_btn.triggered.connect(lambda: self.tabs.currentWidget().reload())
self.navbar.addAction(self.reload_btn)

self.urlbar = QLineEdit()
self.urlbar.returnPressed.connect(self.navigate)
self.navbar.addWidget(self.urlbar)

def navigate(self):
   qurl = QUrl(self.urlbar.text())
   if qurl.scheme() == "":
      qurl.setScheme("http")
   self.tabs.currentWidget().setUrl(qurl)

app = QApplication([])
window = MainWindow()
window.show()
app.exec_()

Output

In the output window above we can see the tabbed browser.

Conclusion

Congratulations! You have completed developing your first PyQt5 tabbed browser. Bookmarks, a history menu, and a search box are just a few of the features that may be added to the programme to make it more tailored to your needs.

Updated on: 21-Dec-2023

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements