Creating a toolbar with icons using QToolbar in PyQt5

Posted by

QToolbar | Create toolbar with icons in PyQt5

QToolbar | Create toolbar with icons in PyQt5

PyQt5 is a set of Python bindings for the Qt application framework and runs on all platforms supported by Qt including Windows, OS X, Linux, iOS and Android. In this article, we will learn how to create a toolbar with icons in PyQt5 using the QToolbar class.

Steps to create a toolbar with icons in PyQt5:

  1. Import necessary modules: First, you need to import necessary modules by using the following code:
  2.     <code>
        import sys
        from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, QToolBar, QIcon
        </code>
      
  3. Create main window: Create a main window by subclassing QMainWindow:
  4.     <code>
        class MainWindow(QMainWindow):
            def __init__(self):
                super().__init__()
                self.initUI()
    
            def initUI(self):
                self.toolbar = self.addToolBar('Toolbar')
        </code>
      
  5. Add actions and icons to the toolbar: Add actions and icons to the toolbar using the addAction() method along with QIcon:
  6.     <code>
        action1 = QAction(QIcon('icon1.png'), 'Action 1', self)
        self.toolbar.addAction(action1)
    
        action2 = QAction(QIcon('icon2.png'), 'Action 2', self)
        self.toolbar.addAction(action2)
        </code>
      
  7. Show the main window: Finally, show the main window by using the following code:
  8.     <code>
        if __name__ == '__main__':
            app = QApplication(sys.argv)
            window = MainWindow()
            window.show()
            sys.exit(app.exec_())
        </code>
      

By following these steps, you can create a toolbar with icons in PyQt5. This can be useful for creating user-friendly and visually appealing GUI applications.