How to add a MenuItem to a ButtonMenu via code?

I want to add a MenuItem of the new m3 theme to a ButtonMenu via code:

from m3._Components.MenuItem import MenuItem
MenuItem(text="My Menu Item")
self.my_button_menu ...   # what do I need here?

I tried to use add_component()" method of the button menu object, or set the menu_items, but this seems to be always None`. What is the correct way to dynamically add menu items, and in which functions is this possible?

What you need to do is just set the menu_items prop to a list that contains your components:

self.test_item = MenuItem(text="My Menu Item")
self.my_button_menu.menu_items = [self.test_item]
3 Likes

That’s it, thank you very much!

1 Like

@duncan_richards12 is correct!

The menu_items property is supposed to make it easier to add components to the ButtonMenu, but it actually just uses add_component and specifies the slot the items need to go into:

    def menu_items(self, value=[]) -> list:
        """A list of components to be added to the menu."""
        for i in value:
            self.add_component(i, slot='anvil-m3-buttonMenu-slot')

So if you wanted more control over how components are added, you can still use add_component, e.g.

i = m3.MenuItem()
self.button_menu_1.add_component(i, slot='anvil-m3-buttonMenu-slot')
3 Likes