PyQt QMenus - Help in creating sub menu items from dictionary


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']}

    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,

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

                # Add in any sub menu items of the main menu
                if 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(
            "name of main menu",
            "Name of new main menu : "
        if ok:
            main_menu_action = QtGui.QAction(new_main_menu, self.qmenu)
            self.main_menus[main_menu_action] = None
    def add_first_tier(self, item):
        first_tier_action = QtGui.QAction(item, self.qmenu)
    def add_second_tier(self, items):
        # how to get the main menu created in add_first_tier()

Many thanks in advance for any replies.



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


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…