E5 - toolbars and menus - QAction
toolbars
QActionclass allows defining abstract user interfaces- this is better than using
QButtonas one only needs to define the triggered action once - this can then be added to both the menu and the toolbar
from PyQt6.QtCore import QSize, Qt
from PyQt6.QtGui import QAction, QIcon, QKeySequence
from PyQt6.QtWidgets import ( QApplication, QCheckBox, QLabel, QMainWindow, QStatusBar, QToolBar)
class Main(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("My App")
toolbar = QToolBar("My Toolbar")
self.addToolBar(toolbar)
button_action = QAction("your button", self)
button_action.setStatusTip('this is your button')
button_action.triggered.connect(self.toolbar_button_clicked)
button_action.setCheckable(True)
toolbar.addAction(button_action)
self.setStatusBar(QStatusBar(self)) ## shows status tip when hovering over the button
def toolbar_button_clicked(self, s):
print("clicked", s)
app = QApplication([])
window = Main()
window.show()
app.exec()
- icons can be added by passing the filename to the class, ie.
QIcon(filename)", and then passing it as the first argument, ie.QAction(QIcon(filename), displayname, self)
menubars
- now to add a menu bar item, the action can be reused
menu = self.menuBar()
file_menu = menu.addMenu("&File")
file_menu.addAction(button_action)
- here,
alt + Fwould jump to the menu item
accelerator keys
adding & before a menu title enables user to jump to the menu item by pressing alt+ key
setKeySequencecan be used to add keyboard shortcuts forQAction
button_action.setShortcut(QKeySequence("Ctrl+p"))