0

I want to make my own menu bar. I have found a way to add actions to a QPushButton:

Source: https://www.youtube.com/watch?v=Aj-Q8pu_HG0

def add_menu(data,menu_obj):
    if isinstance(data,dict):
        for k,v in data.items():
            sub_menu = QtWidgets.QMenu(k,menu_obj)
            menu_obj.addMenu(sub_menu)
            add_menu(v,sub_menu)
    elif isinstance(data,list):
        for element in data:
            add_menu(element,menu_obj)       
    else:
        print(data)
        action = menu_obj.addAction(data)
        #action.setIconVisibleInMenu(False) 
        if action == "load":
            action.triggered.connect(lambda : print("load"))
        elif action == "new":
            action.triggered.connect(lambda : print("new"))
        elif action == "save":
            action.triggered.connect(lambda : print("save"))

file_menu = [
    "new","load","save"
]


menu = QtWidgets.QMenu()
menu.setStyleSheet(menu_style)
self.pushButton_file.setMenu(menu)
add_menu(file_menu,menu)

However, I am not able to add functions to specific items. What I would ideally be able to do is:

self.menuitem_new.triggered.connect(lambda:print("NEW")).

Is that possible ?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
david 11
  • 75
  • 8
  • your question is unclear. what is `self.menuitem_new`? – eyllanesc Aug 02 '21 at 17:45
  • sorry. i ment tht i have one of the new actions as an object that i can check. like in the list there are the actions ["new","load","save"]... if i make a menu in qt designer i just name them menuitem_new, menuitem_load and so on. so for example i can connec them all to the same function, which checks the selected item and unchecks the others. but if i add menu items to buttons i can not uncheck the acitons, as i dont know how to access them (from other actions) – david 11 Aug 02 '21 at 18:10
  • 1
    @david11 Why have you copied that code from youtube if it doesn't do what you want? There are much simpler ways to add a menu to a button than that. Do you really need to create the menu-items from a list of strings? What exactly are you trying to achieve? – ekhumoro Aug 02 '21 at 19:08
  • Zetcode has a nice [tutorial on creating menus](https://zetcode.com/gui/pyqt5/menustoolbars/). – bfris Aug 03 '21 at 00:26

0 Answers0