import sys from PySide.QtGui import QApplication, QMainWindow, QAction, QActionGroup, QMenu class Example(QMainWindow): def __init__(self): super().__init__() group = QActionGroup(self) action1 = QAction("Action 1", self) action2 = QAction("Action 2", self) group.addAction(action1) group.addAction(action2) action1.setCheckable(True) action2.setCheckable(True) file_menu = QMenu("File", self) file_menu.addAction(action1) file_menu.addAction(action2) file_menu.addSeparator() self.menuBar().addMenu(file_menu) self.setGeometry(100, 100, 300, 200) self.setWindowTitle("Example") if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() ex.show() sys.exit(app.exec_())
import sys from PySide.QtGui import QApplication, QMainWindow, QAction, QActionGroup, QMenu class Example(QMainWindow): def __init__(self): super().__init__() group = QActionGroup(self) action1 = QAction("Action 1", self) action2 = QAction("Action 2", self) group.addAction(action1) group.addAction(action2) action1.setCheckable(True) action2.setCheckable(True) action1.setChecked(True) self.toolbar = self.addToolBar("Toolbar") self.toolbar.addAction(action1) self.toolbar.addAction(action2) self.setGeometry(100, 100, 300, 200) self.setWindowTitle("Example") if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() ex.show() sys.exit(app.exec_())In this example, we create an instance of QActionGroup and add two QAction objects to it. We also set the actions to be checkable and set the first action to be checked by default. We then add the actions to a toolbar using addToolBar() function. This allows the user to select one of the actions and toggle it on and off with the group handling the behavior. Package library: PySide.