[GIS] Checking if subMenu item exists

pyqgisqgis-plugins

I have created a few toolbars all of them have their own menu item in the main menu of QGIS.
Now I want to have them as sub-menus in one menu item, I managed to check if my menu item exists like so.

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

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

But now when the menu exists already i need to check if a sub-menu already exists of if i have to create it.
I tried something like this but it still create the submenu again if the plugin is reloaded.

self.menuStrasse = self.menu.findChild(QMenu, '&MySubMenu')

if not self.menuStrasse:
   self.menuStrasse = self.menu.addMenu( "MySubMenu")

self.menuStrasse.addActions( [self.action1,self.action2])

Can someone point me in the right direction?

Best Answer

Instead of checking if the submenu exists, you could just check if the main menu exists (which you have done) and if it doesn't, add the menu and the submenus at the same time:

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

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

    self.menuStrasse = self.menu.addMenu( "MySubMenu")
    self.menuStrasse.addActions( [self.action1,self.action2])

This should avoid creating duplicate submenus.


Edit:

An alternative could be to check all submenu actions in the main menu by storing them in a list. If 'MySubMenu' does not exist in the list, it will be created:

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

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

# Create list containing submenu actions from main menu
submenus = []
for item in self.menu.actions():
    submenus.append(item.text())

# Check submenu action list to see if 'MySubMenu' exists
submenu_list = [x for x in submenus if x == 'MySubMenu']
# If 'MySubMenu' is not in above list (i.e. does not exist), create it
if not submenu_list:
    self.menuStrasse = self.menu.addMenu( 'MySubMenu')
Related Question