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:
- Import necessary modules: First, you need to import necessary modules by using the following code:
- Create main window: Create a main window by subclassing QMainWindow:
- Add actions and icons to the toolbar: Add actions and icons to the toolbar using the addAction() method along with QIcon:
- Show the main window: Finally, show the main window by using the following code:
<code> import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, QToolBar, QIcon </code>
<code> class MainWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.toolbar = self.addToolBar('Toolbar') </code>
<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>
<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.