PyQt QMenus - Help in creating sub menu items from dictionary


#1

Hi everyone, I need some advice/ help in QMenus.

Currently I am trying to create/ add QMenus that are read off from a dictionary values.
However, the QMenus I am going for, have sub-menu items contain within.

And while I am able to create the main menu item from the dictionary, I am having trouble getting the sub menu items to be added into the created main menu.

In my following code, while I am able to get mains created, its sub items - eastern and western, I am unable to get it populated under mains.

class Example(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Example, self).__init__(parent)
        self.main_menus = defaultdict(list)
        
        self.menu_listing = {'mains': ['eastern', 'western'], 'drinks': ['water', 'beer', 'soda']}
        self.initUI()
        

    def initUI(self):         
        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Context menu')    

        self.qmenu = QtGui.QMenu()
        add_item_action = QtGui.QAction('Add new main item', self,
            triggered=self.add_main_menu)
        self.qmenu.addAction(add_item_action)
        self.qmenu.addSeparator()

        # Creates/ Add in new menu items if there is an existing menu listing
        if self.menu_listing:
            for main_menu in self.menu_listing:
                self.add_first_tier(main_menu)

                # Add in any sub menu items of the main menu
                if self.menu_listing[main_menu]:
                    self.add_second_tier(self.menu_listing[main_menu])
                

    def contextMenuEvent(self, event):
        action = self.qmenu.exec_(self.mapToGlobal(event.pos()))

    def add_main_menu(self):
        new_main_menu, ok = QtGui.QInputDialog.getText(
            self,
            "name of main menu",
            "Name of new main menu : "
        )
        if ok:
            main_menu_action = QtGui.QAction(new_main_menu, self.qmenu)
            self.qmenu.addAction(main_menu_action)
            self.main_menus[main_menu_action] = None
    
    def add_first_tier(self, item):
        first_tier_action = QtGui.QAction(item, self.qmenu)
        self.qmenu.addAction(first_tier_action)
        
    def add_second_tier(self, items):
        # how to get the main menu created in add_first_tier()
        pass

Many thanks in advance for any replies.


#2

Hey,

This might help:

That function recursively generates menus from dictionaries. It uses the keys as labels, and the values as callables, but if the value is a dictionary then it calls itself to generate a sub menu. This allows you to have as many depths as you want within the dictionary.

Hope that helps! Mike


#3

Hi Mike, thanks for getting back… It does not seems to be working for me though where my actual menu - self.qmenu is even populating with any items…