QML 序列类型
对于每个对象类型和值类型,都会自动提供一个序列类型来存储该类型的多个实例。您可以使用list
关键字来创建序列类型的属性:
import QtQml QtObject { property list<int> ints: [1, 2, 3, 4] property list<Connection> connections: [ Connection { // ... }, Connection { // ... } ] }
值类型的序列实现为QList ,对象类型的序列实现为QQmlListProperty 。
QML 中的序列一般表现得像 JavaScriptArray
类型,但由于在实现中使用了 C++ 存储类型,所以有一些重要的区别:
- 从序列中删除一个元素会导致一个默认构造的值取代该元素,而不是
undefined
值。 - 将序列的
length
属性设置为大于其当前值的值,将导致序列填充为指定长度的默认构造元素,而不是undefined
元素。 - Qt XML 容器类支持有符号(而非无符号)整数索引;因此,尝试访问任何大于qsizetype 可容纳最大数量的索引都将失败。
如果您希望从序列中删除元素,而不是简单地用默认构造值替换它们,请不要使用索引删除操作符 (delete sequence[i]
),而是使用splice
函数 (sequence.splice(startIndex, deleteCount)
)。
一般来说,QMetaSequence 可识别的任何容器都可以通过Q_PROPERTY 或Q_INVOKABLE 方法从 C++ 传递到 QML。这包括但不限于所有已注册的QList,QQueue,QStack,QSet, std::list, std::vector 中包含的标有Q_DECLARE_METATYPE 的类型。
通过QMetaSequence 使用序列会导致昂贵的数据转换。为了避免转换,可以使用 C++ 中的QML_SEQUENTIAL_CONTAINER 注册自己的匿名序列类型。以这种方式注册的类型与预定义的序列类型一样,并按原样存储。不过,它们没有 QML 名称。
警告: 作为QList 或std::vector
等 C++ 容器存储的序列会受到QML 值类型和序列引用的影响,因此应小心处理。QQmlListProperty 不受影响,因为它只是底层容器的视图。C++ 标准容器(如std::vector
)不是隐式共享的。因此,复制它们总是会产生深拷贝。由于从属性中读取的序列总是至少要复制一次,因此将此类容器用作 QML 序列相当昂贵,即使您不从 QML 中修改它们也是如此。
QtQml 模块包含一些你可能想使用的sequence types 。
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.