Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Creating dynamic submenus with repeaters?



  • Hi!
    Does anyone know how to dynamically add subMenus to another Menu?

    I have a dynamic number of 'Menu' that I would like to add to another Menu using a repeater.
    Sadly, while I've already successfully used repeaters to add 'MenuItem' to another Menu, I get the following error when trying to add submenus (Menu) instead of menuItems:

    "QML Component: Delegate must be of Item type"

    I've tried multiple approaches to counter the issue, starting with wrapping the menu in an Item, which did not work.

    Looking fwd to your input!



  • @lagarkane hi
    the complete error was

    qrc:/main.qml:29:12: QML Component: Delegate must be of Item type
    ASSERT: "objectRef == 0" in file types\qqmldelegatemodel.cpp, line 2079
    19:23:26: Le programme s'est terminé subitement.
    

    thats because Menu is a Popup, but delegate must be Item

    i used Repeater with a Loader and wrapped Menu in a Component, it worked

    import QtQuick 2.12
    import QtQuick.Window 2.12
    import QtQuick.Controls 2.12
    
    ApplicationWindow {
        id: root
        width: 800
        height: 600
        visible: true
    
        Button {
            id: fileButton
            text: "File..."
            onClicked: menu.open()
    
            Menu {
                id: menu
                y: fileButton.height
    
                MenuItem{
                    text: "item 1"
                }
    
                Repeater{
                    id:menuLoader
                    model:3
                    Loader{
                        sourceComponent: sb
                        onStatusChanged:status === Loader.Ready ? console.log("sub men "+index + " loaded") : console.log("!ok")
                    }
                }
            }
        }
    
        //--
        Component{
            id:sb
            Button{ // you can delete button if you want.
                text: "New"
                onClicked: sub.open()
                Menu{
                    id: sub
                    MenuItem{
                        text: "sub menu item"
                    }
                }
            }
        }
    }
    
    
    

  • Qt Champions 2018

    Use an Instantiator instead of a Repeater


Log in to reply