本页内容

ObjectModel QML Type

定义一组将用作模型的项目。更多...

Import Statement: import QtQml.Models

属性

关联属性

方法

  • void append(object item)
  • void clear()
  • QtObject get(int index)
  • void insert(int index, object item)
  • void move(int from, int to, int n)
  • void remove(int index, int n)

详细说明

ObjectModel 包含将在视图中使用的视觉项。当在视图中使用 ObjectModel 时,该视图无需委托,因为 ObjectModel 本身已包含视觉委托(即各项)。

项目可通过index 附加属性确定其在模型中的索引。

下面的示例在ListView 中放置了三个彩色矩形。

import QtQuick 2.0
import QtQml.Models 2.1

Rectangle {
    ObjectModel {
        id: itemModel
        Rectangle { height: 30; width: 80; color: "red" }
        Rectangle { height: 30; width: 80; color: "green" }
        Rectangle { height: 30; width: 80; color: "blue" }
    }

    ListView {
        anchors.fill: parent
        model: itemModel
    }
}

三个彩色矩形在 ListView 中堆叠

另请参阅 “Qt Quick 示例——视图”。

属性文档

count : int [read-only]

模型中的项目数量。此属性为只读。

附加属性文档

ObjectModel.index : int [attached]

此附加属性保存了该委托在模型中项的索引。

它附属于该委托的每个实例。

方法文档

void append(object item)

将一个新的item 追加到模型末尾。

objectModel.append(objectComponent.createObject())

另请参阅 insert() 和remove()。

void clear()

清除模型中的所有项目。

另请参阅 append() 和remove()。

QtObject get(int index)

返回模型中位于 `index ` 位置的项目。这使得可以通过 JavaScript 访问或修改该项目:

Component.onCompleted: {
    objectModel.append(objectComponent.createObject())
    console.log(objectModel.get(0).objectName);
    objectModel.get(0).objectName = "first";
}

index 必须是列表中的一个元素。

另请参阅 append()。

void insert(int index, object item)

将一个新的item 插入到模型中,位置为index 。

objectModel.insert(2, objectComponent.createObject())

该index 必须指向列表中的现有项,或者位于列表末尾之后的一项(相当于追加操作)。

另请参阅 append() 和remove()。

void move(int from, int to, int n = 1)

将n 中的项目from 移动一个位置,to 移动另一个位置。

源范围和目标范围必须存在;例如,要将前3个项移动到模型末尾:

objectModel.move(0, objectModel.count - 3, 3)

另请参阅 append()。

void remove(int index, int n = 1)

从模型中移除位于index 的n 项。

另请参阅 clear()。

© 2026 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.