0

When using a ListModel for a repeater, if a property is not set in the first element of the model, then it is not considered in the following elements. Why?


import QtQuick 2.7
import QtQuick.Controls 2.3

Item{
    id: root
    property var labels: ListModel{}
    Button{
        text: 'create labels'
        onClicked:{
            root.labels.append({})
            root.labels.append({name: '2'})
            root.labels.append({name: '3'})
        }
    }
    Column{
        x: 10
        y: 200
        spacing: 2
        Repeater{
            model:  root.labels
            Button{
                width: 120
                height: 30
                text: model.name
            }
        }
    }
}

This code is ok:

....
        onClicked:{
            root.labels.append({name: '1'})
            root.labels.append({})
            root.labels.append({name: '3'})
        }
 ....


eyllanesc
  • 235,170
  • 19
  • 170
  • 241
developer
  • 9
  • 1

1 Answers1

1

It doesn't work because the roles of the ListModel get evaluated based on its first element. The property of the first element defines the roles of the model. If you had other properties in the following elements, those will be ignored.

That behavior is the default one when the dynamicRoles property is not set to true. When set to true, the model will recalculate its roles for each inserted element and emit a modelReset every time the roles change. This is costly and not generally needed so its disabled by default.

GrecKo
  • 6,615
  • 19
  • 23