Thursday, July 8, 2010

QActionGroup and exclusive menu actions

Today I was working on exclusive menu action selection in PyQt4 and got stuck. After some struggling, I managed to find it out. Now I want to share it with you.

What is exclusive menu action? It's a menu item, when you select it, its friends are deselected. When one of its friends is selected, it gets deselected. It's like a radio button group in a menu.

We're going to use QMenu, QAction and QActionGroup for this purpose.
# assume we are in a QMainWindow method, constructing the menu.

menu = QMenu('Alignment', self.menuBar())
menuGroup = QActionGroup(menu)
menuGroup.setExclusive(True)

left = QAction('left', menuGroup)
center = QAction('center', menuGroup)
right = QAction('right', menuGroup)

actions = (left, center, right)
map(menu.addAction, actions)
map(lambda action: action.setCheckable(True), actions)

center.setChecked(True)
self.menuBar().addMenu(menu)


In this way, you are able to select either left or center or right for alignment submenu.