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:
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: