For every
对象类型
and
值类型
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
数组
type, with some important differences which result from the use of a C++ storage type in the implementation:
undefined
值。
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 than
undefined
元素。
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
函数 (
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 .
使用序列凭借 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.
警告:
Sequences stored as a C++ container like
QList
or
std::vector
are subject to the effects caused by
QML 值类型和序列引用
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.