Creating a QMenubar with Icons and Shortcuts in PyQt5
PyQt5 is a popular Python library for creating GUI applications. One of the key components in building a GUI application is creating a menu bar. A menu bar typically contains a set of menus, each of which may contain a list of actions. In this article, we will look at how to create a menu bar with icons and shortcuts in PyQt5.
Step 1: Import the necessary modules
First, make sure you have PyQt5 installed. If not, you can install it using pip:
pip install pyqt5
Then, import the necessary modules in your Python script:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, QMenuBar
from PyQt5.QtGui import QIcon
Step 2: Create a QMainWindow
Create a subclass of QMainWindow, which will serve as the main window for your application:
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# Set window title
self.setWindowTitle('Menu Bar Example')
Step 3: Create a Menu Bar with Icons and Shortcuts
Next, create a menu bar and add menus and actions to it:
menubar = self.menuBar()
# Create File menu
file_menu = menubar.addMenu('File')
# Create a QAction for New action with icon and shortcut
new_action = QAction(QIcon('new.png'), '&New', self)
new_action.setShortcut('Ctrl+N')
file_menu.addAction(new_action)
# Create a QAction for Open action with icon and shortcut
open_action = QAction(QIcon('open.png'), '&Open', self)
open_action.setShortcut('Ctrl+O')
file_menu.addAction(open_action)
# Create a QAction for Save action with icon and shortcut
save_action = QAction(QIcon('save.png'), '&Save', self)
save_action.setShortcut('Ctrl+S')
file_menu.addAction(save_action)
Step 4: Run the application
Finally, create an instance of MyWindow and run the application:
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
Conclusion
Creating a menu bar with icons and shortcuts in PyQt5 is essential for building user-friendly GUI applications. By following the steps outlined in this article, you can easily create a menu bar with icons and shortcuts in your PyQt5 application.
Thanks, this was a very helpful tutorial!