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.action = QAction(QIcon(":/plugins/Trial/icon.png"),"Trial plugin", self.iface.mainWindow())

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?

  • 1
    global name 'QMenu' is not defined – Bayanaa Jun 2 '18 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 '19 at 12:05

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 )
  • 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 '19 at 12:06
  • 1
    Chances are you're missing the QMenu import. For QGIS v3.x: from qgis.PyQt.QtWidgets import QMenu – Germán Carrillo Feb 2 '19 at 18:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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