Search code examples
qtlistviewqmlqt-quick

QML dynamic list of widgets


I have a QStringList property, and I basically want to turn that into a group of radio buttons dynamically, so that when the QStringList property changes the number of buttons and their labels is automatically updated.

I can sort of do it with a ListView, but it has problems:

  1. It's not really a desktop widget so you have all the mobile bounciness.
  2. I can't get the ListView selection and the radio button checks to interact nicely.

Here's my attempt anyway. I'd ideally like to do it without a ListView though:

        ListView {
            id: myList
            orientation: ListView.Horizontal

            ExclusiveGroup {
                id: myListExclusiveGroup
            }

            Component {
                id: myDelegate
                RadioButton {
                    text: modelData
                    onCheckedChanged: {
                        if (checked)
                            myList.currentIndex = index
                    }
                    exclusiveGroup: myListExclusiveGroup
                }
            }

            model: myListOfStrings
            delegate: myDelegate
            focus: true
        }

Solution

  • Thanks to koopajah, I changed it to use Repeater and it works now. Note that it seems Repeater adds everything to the end of its parent's children, which means you can't rely on its position in a layout - you have to put it inside another layout, for example like this:

            ExclusiveGroup {
                id: myListExclusiveGroup
            }
            RowLayout {
                Repeater {
                    id: myList
    
                    RadioButton {
                        text: modelData
                        exclusiveGroup: myListExclusiveGroup
                    }
    
                    model: myListOfStrings
                    focus: true
                }
            }