Repeater QML Type
使用提供的模型实例化若干基于项目的组件。更多
Import Statement: | import QtQuick |
Inherits: |
属性
信号
- itemAdded(int index, Item item)
- itemRemoved(int index, Item item)
方法
- Item itemAt(index)
详细说明
Repeater 类型用于创建大量类似的项目。与其他视图类型一样,Repeater 也有一个model 和一个delegate :对于模型中的每个条目,委托都是在使用模型数据种子的上下文中实例化的。Repeater 项目通常包含在Row 或Column 等定位器类型中,以便直观地定位 Repeater 创建的多个委托项目。
下面的 Repeater 在Row 中创建了三个Rectangle 项目实例:
import QtQuick Row { Repeater { model: 3 Rectangle { width: 100; height: 40 border.width: 1 color: "yellow" } } }
Repeater 的model 可以是任何支持的数据模型。此外,与其他视图的委托一样,Repeater 委托可以访问其在 Repeater 中的索引以及与委托相关的模型数据。详情请参阅delegate 属性文档。
由中继器实例化的项目会作为中继器父节点的子节点按顺序插入。插入是从中继器在父堆叠列表中的位置后立即开始的。这样,中继器就可以在布局中使用。例如,下面的中继器项目堆叠在红色矩形和蓝色矩形之间:
Row { Rectangle { width: 10; height: 20; color: "red" } Repeater { model: 10 Rectangle { width: 20; height: 20; radius: 10; color: "green" } } Rectangle { width: 10; height: 20; color: "blue" } }
注: Repeater 项目拥有其实例化的所有项目。删除或动态销毁 Repeater 创建的项目会导致不可预知的行为。
使用 Repeater 时的注意事项
中继器类型会在首次创建中继器时创建其所有委托项。如果存在大量委托项,且并非所有委托项都需要同时可见,那么这种创建方式就会效率低下。如果是这种情况,可以考虑使用其他视图类型,如ListView (只有在滚动到视图时才会创建委托项),或者使用Dynamic Object Creation 方法在需要时创建项目。
此外,请注意 Repeater 是基于Item 的,只能重复Item 派生的对象。例如,它不能用于重复 QtObjects:
// bad code: Item { // Can't repeat QtObject as it doesn't derive from Item. Repeater { model: 10 QtObject {} } }
属性文档
count : int |
此属性保存模型中的项目数。
注意: 如果 Repeater 正在实例化委托,或者设置不正确,那么由 count 报告的模型中的项目数可能与创建的委托数不同。
delegate : Component |
model : var |
为中继器提供数据的模型。
该属性可设置为任何支持的数据模型:
- 一个数字,表示中继器要创建的委派数目
- 一个模型(如ListModel 项,或QAbstractItemModel 子类)
- 字符串列表
- 对象列表
模型的类型会影响delegate 所显示的属性。
另请参阅 数据模型。
信号文档
当一个项目被添加到中继器时,就会发出该信号。index 参数包含项目插入中继器的索引,而item 参数则包含已添加的Item 。
注: 相应的处理程序是onItemAdded
。
当项目从中继器中移除时,将发出该信号。index 参数包含项目从中继器中移除时的索引,而item 参数则包含被移除的Item 。
如果item 是由该中继器创建的,则不要保留对它的引用,因为在这种情况下,它将在信号处理后不久被删除。
注: 相应的处理程序是onItemRemoved
。
方法文档
© 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.