2
votes

I have a dynamicaly created Menu. The code below is just to understand the hierarchy

Menu {
    id: mainMenu
    MenuItem {
       text: "item"
    }
    Menu {
       title: "submenu"
       MenuItem {
           text: "submenuitem"
        }
    }   
}

Now I need to remove all mainMenu's content. As I can see in the documentation, Menu have methods removeItem, takeItem and takeMenu. Using takeMenu and count property I can access menu's children and remove them recursively. But what if I don't know the order and type of menu items? Item has not property count. I need some universal solution that can remove the item itself, and if it is a menu then remove all it's children.

1
Did you take a look at the Instantiator in Menu to dynamically create your menu ? doc.qt.io/qt-5/qml-qtquick-controls-menu.html#items-prop - ymoreau
Yes, I did. The menu is created using custom Instantiator. So I don't clearly understand how to delete its children from qml, not from c++ - Roman Sverdlov
The short example of the doc shows how it works. It's a model that you populate, so you just need to clear your model and your instantiator can handle it onObjectRemoved: recentFilesMenu.removeItem(object) - ymoreau

1 Answers

3
votes

I don't know if it's the cleanest solution, but it works well to clear your example.

while(mainMenu.items.length > 0)
    mainMenu.removeItem(mainMenu.items[0]);

You don't need to go recursively because when you remove an Item, all its childItems are removed with it.