6

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?

2
  • 1
    global name 'QMenu' is not defined
    – Bayanaa
    Jun 2, 2018 at 3:52
  • I am getting the same issue - "QMenu is not defined" when I add this and the code below into a working plugin.
    – GeorgeC
    Feb 2, 2019 at 12:05

1 Answer 1

10

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 )
5
  • Carrillo - I am getting the same issue - "QMenu is not defined" when I add this into a working plugin. Is there somewhere this should be defined?
    – GeorgeC
    Feb 2, 2019 at 12:06
  • 1
    Chances are you're missing the QMenu import. For QGIS v3.x: from qgis.PyQt.QtWidgets import QMenu Feb 2, 2019 at 18:49
  • How would you go about not removing both plugins when calling self.iface.removePluginMenu in the unload method? Sep 4, 2020 at 10:28
  • I think you would need to check if you're the last plugin left in the menu and only then remove it. Sep 4, 2020 at 12:03
  • 1
    I create menu bar as mentioned above but when I reloading its creating another menu how to Unload the menu bar. please provide code snippet Dec 8, 2020 at 9:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.