20
votes

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.

3
property variant recentFiles: [] - folibis
"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.)" - dtech

3 Answers

14
votes
Settings {
    property var recentFiles: []
}

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

10
votes

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

7
votes

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