Timmmm
Timmmm

Reputation: 96547

How to declare list property in QML

How do I declare a list property in QML (for use with Qt.labs.settings in my case):

Settings {
    property list recentFiles: []
}

Does not work. I've tried many other options: list<string>, string[], etc. None seem to work.

Upvotes: 26

Views: 35966

Answers (4)

gatis paeglis
gatis paeglis

Reputation: 611

!!! NOTE: this info is out-of-date and not accurate for recent Qt 6.x version. For more info, see the comment under this post.

Since you were asking about the list property (the 'list' keyword), then the following syntax seems to work:

property list<Rectangle> rectList: [
    Rectangle { id: a; },
    Rectangle { id: b; }
]

Rectangle { id: c }

Component.onCompleted: {
    console.log("length: " + rectList.length)
    rectList.push(c)
    console.log("length: " + rectList.length)
}

This will print

qml: length: 2
qml: length: 3

But I see that 'rectList' would accept also the following:

MouseArea { id: mArea; }
..
rectList.push(mArea)

Which does not make sense. And command suggestion / auto completion does not work with this syntax in Qt Creator. I guess this is some kind of legacy syntax, which should not be used in new apps. You should use instead what was suggested by other answers:

property var myList: []

Then you get better support by Qt Creator.

And the documentation for 'list' says [1]:

"A list can only store QML objects, and cannot contain any basic type values. (To store basic types within a list, use the var type instead.)"

So the following won't compile:

property list<int> intList: []

The same docs also say:

"Note: The list type is not recommended as a type for custom properties. The var type should be used instead for this purpose as lists stored by the var type can be manipulated with greater flexibility from within QML."

[1] https://doc.qt.io/qt-5/qml-list.html

Upvotes: 13

ulf
ulf

Reputation: 1

list currently only accepts object types. int is a value type. list should be preferred over var where possible because it is typed.

Upvotes: 0

Artem Zaytsev
Artem Zaytsev

Reputation: 1695

A list can only store QML objects, and cannot contain any basic type values

string is a basic type, so you can't store it in list. For that purpose you'd better use property var recentFiles

Upvotes: 9

fat
fat

Reputation: 7103

Settings {
    property var recentFiles: []
}

http://doc.qt.io/qt-5/qml-var.html

Upvotes: 17

Related Questions