Skip to content Skip to sidebar Skip to footer

How To Initialize Qml Property List In A Loop?

I have the qml list property: Item { property list items: [ SomeItem { num: 0 }, SomeItem { num: 1 }, SomeItem { num: 2 }, ...

Solution 1:

No.

The documentation for list describes the ways that it can be used:

A list value can be accessed in a similar way to a JavaScript array:

  • Values are assigned using the [] square bracket syntax with comma-separated values
  • The length property provides the number of items in the list
  • Values in the list are accessed using the [index] syntax

You're better off using a Repeater:

Repeater {
    model: 100

    delegate: SomeItem {
        num: index
    }
}

Solution 2:

What you try to do makes no sense. And is completely redundant. And impossible.

The id property is not a string, nor can it be a number.

In your particular case you want a number id equal to the index of each object in the list, which aside from impossible is also unnecessary. Instead you can access each object easily by using items[index].

If for some reason you really need to assign and use dynamic identifiers, you can use a JS object, which will allow you to do string key lookup rather than integer index:

    Item {        
        property var lookup: new Object

        Component {
            id: test

            QtObject {
                property string name
            }
        }

        Component.onCompleted: {
            lookup["John"] = test.createObject(null, { "name" : "JohnDoe" })
            lookup["Jane"] = test.createObject(null, { "name" : "JaneDoe" })

            console.log(lookup["John"].name) // outputs JohnDoe
            console.log(lookup["Jane"].name) // outputs JaneDoe
        }
    }

Post a Comment for "How To Initialize Qml Property List In A Loop?"