Friday 27 December 2019

pyqgis - Adding multiple plugins to custom menu in QGIS


I am new to Python and QGIS and attempting to create some plugins to replicate in-house tools used in other GIS programs. I have added a custom menu using Python and added the plugin to the menu using the following code within the initGui method:


self.menu = QMenu("&Menu Name", self.iface.mainWindow().menuBar())
actions = self.iface.mainWindow().menuBar().actions()
lastAction = actions[-1]

self.iface.mainWindow().menuBar().insertMenu(lastAction,self.menu)
self.action = QAction(QIcon(":/plugins/Trial/icon.png"),"Trial plugin", self.iface.mainWindow())
self.action.triggered.connect(self.run)
self.menu.addAction(self.action)

However, if I try and add another plugin to the same menu I end up with duplicated menu item names with only one plugin in the menu, rather than all the plugins under the same menu. Is there a way of adding multiple plugins to an existing custom menu item?



Answer



There is a way. You need to check whether your menu is already present in the QGIS Menu Bar. If so, you can reuse it, otherwise, you create it.


In the initGui method of each of your plugins, add the following code (see comments for details):


# Check if the menu exists and get it

self.menu = self.iface.mainWindow().findChild( QMenu, '&My tools' )

# If the menu does not exist, create it!
if not self.menu:
self.menu = QMenu( '&My tools', self.iface.mainWindow().menuBar() )
self.menu.setObjectName( '&My tools' )
actions = self.iface.mainWindow().menuBar().actions()
lastAction = actions[-1]
self.iface.mainWindow().menuBar().insertMenu( lastAction, self.menu )


# Finally, add your action to the menu
self.menu.addAction( self.action )

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...