[GIS] Making QGIS buttons and the Plugin button mutually exclusive

pyqgispythonqgisqgis-pluginstoolbar

I've added a toolbar to the QGIS main window and I've added some checkable buttons to the toolbar.

How can I make my checkable buttons untoggle QGIS default toolbars' checkable buttons? That is, when I activate my button by clicking on it, I want QGIS default buttons to be deactivated.

Is there a way to get the QGIS main window's QButtonGroup?

Best Answer

You can access QGIS toolbar buttons (actions) by using the iface object (docs here). From those actions you can create a QActionGroup and add your custom action making all actions mutually exclusive.

The following code snippet shows you how to do it, step by step. I've put the code snippet in the initGui(self) method of my test plugin.

# Make sure your action can be toggled 
self.action.setCheckable( True )

# Build an action list from QGIS navigation toolbar
actionList = self.iface.mapNavToolToolBar().actions()

# Add actions from QGIS attributes toolbar (handling QWidgetActions)
tmpActionList = self.iface.attributesToolBar().actions()        
for action in tmpActionList:
    if isinstance(action, QWidgetAction):
        actionList.extend( action.defaultWidget().actions() )
    else:
        actionList.append( action ) 
# ... add other toolbars' action lists...

# Build a group with actions from actionList and add your own action
group = QActionGroup( self.iface.mainWindow() )
group.setExclusive(True)
for action in actionList:
    group.addAction( action )
group.addAction( self.action )

You can get a demo plugin showing this behavior from here. In the README file you have installation and configuration instructions.

After installing the demo plugin, you can notice your plugin button deactivates QGIS buttons and the other way around.

Note: I've only included actions from the Navigation and Attributes QGIS toolbars. You might need to add other QGIS toolbar actions as well. All QGIS toolbars you can get are exposed in the QgisInterface.