Reputation: 371
I'm running a code that adds a menu to the toolbar. But when I run it again, it adds another menu to the toolbar with the same name.
How do I get rid of the first menu? I found "setVisible=True", but I don't know how to find the menu whom I should set this to. How can I achieve that?
Thanks!
def run(self)
with open(menubar_file) as file:
yaml_content = file.read()
menu_dict = yaml.load(yaml_content, Loader=yaml.FullLoader)
for menu, menubar_content in menu_dict.items():
q_menubar = self.win.menubar.addMenu(menu). // How do I do "if self.win.menubar contains menu, delete(menu)?"
# rest of code
Couldn't find it in the documentation... Thanks in advance!
Upvotes: 2
Views: 663
Reputation: 48231
Every QWidget has a list of QActions, they are normally added using addAction()
or addActions()
, but QMenu and QMenuBar do that also when using addMenu()
.
Each QMenu also has a menuAction()
, which is the action used when the menu is added to a QMenuBar or to QMenu as a sub menu.
Using actions()
you can access the list of each action added to a certain widget, and in the case of QMenuBar it will list every menuAction()
of each menu.
Note that:
menuAction()
is menu()
, which returns the QMenu associated with that action;If you need to replace each existing menu based on its title, you can cycle through all actions, check if the name matches and it's a menu, and then clear it before replacing its contents:
def run(self)
with open(menubar_file) as file:
yaml_content = file.read()
menu_dict = yaml.load(yaml_content, Loader=yaml.FullLoader)
menus = {a.text():a.menu() for a in self.win.menubar.actions() if a.menu()}
for menu_name, menubar_content in menu_dict.items():
menu = menus.get(menu_name)
if menu is None:
self.win.menubar.addMenu(menu_name)
else:
menu.clear()
# ...
Upvotes: 1