QML Sequence Types
For every object type and value type a sequence type for storing multiple instances of the type is automatically made available. You can use the list
keyword to create properties of sequence types:
import QtQml QtObject { property list<int> ints: [1, 2, 3, 4] property list<Connection> connections: [ Connection { // ... }, Connection { // ... } ] }
Sequences of value types are implemented as QList and sequences of object types are implemented as QQmlListProperty.
Sequences in QML generally behave like the JavaScript Array
type, with some important differences which result from the use of a C++ storage type in the implementation:
- Deleting an element from a sequence will result in a default-constructed value replacing that element, rather than an
undefined
value. - Setting the
length
property of a sequence to a value larger than its current value will result in the sequence being padded out to the specified length with default-constructed elements rather thanundefined
elements. - The Qt container classes support signed (rather than unsigned) integer indexes; thus, attempting to access any index greater than the maximum number qsizetype can hold will fail.
If you wish to remove elements from a sequence rather than simply replace them with default constructed values, do not use the indexed delete operator (delete sequence[i]
) but instead use the splice
function (sequence.splice(startIndex, deleteCount)
).
In general any container recognizable by QMetaSequence can be passed from C++ to QML via Q_PROPERTY or Q_INVOKABLE methods. This includes, but is not limited to, all registered QList, QQueue, QStack, QSet, std::list, std::vector that contain a type marked with Q_DECLARE_METATYPE.
Using a sequence via QMetaSequence results in expensive data conversions. To avoid the conversions you can register your own anonymous sequence types using QML_SEQUENTIAL_CONTAINER from C++. Types registered this way behave like the pre-defined sequence types and are stored as-is. However, they have no QML names.
Warning: Sequences stored as a C++ container like QList or std::vector
are subject to the effects caused by QML Value Type and Sequence References and should thus be handled with care. QQmlListProperty is not affected since it is only a view for an underlying container. C++ standard containers such as std::vector
are not implicitly shared. Therefore, copying them always produces a deep copy. Since a sequence read from a property always has to be copied at least once, using such containers as QML sequences is rather expensive, even if you don't modify them from QML.
The QtQml module contains a few sequence types you may want to use.