VisualItemModel允许使用QML项目作为模型,该模型同时包含了数据和委托,在VisualItemModel中的子项目提供了委托的内容,该模型没有提供任何角色,(现在一般使用ObjectModel代替VisualItemModel)
ObjectModel(对象模型)
使用时需要导入: 根据版本号变动
import QtQml.Models 2.1
属性:
count | 项目的个数 |
ObjectModel.index | 索引, 此附加属性在模型中保存此委托项的索引。 它附加到委托的每个实例。 |
方法:
append() | 添加 |
clear() | 清除全部 |
get() | 获取 |
insert() | 插入 |
move() | 移动 |
remove() | 删除 |
使用 VisualItemModel
import QtQuick 2.9
Rectangle {
width:400;height:400
VisualItemModel {
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
}
}
等价与:
import QtQuick 2.9
import QtQml.Models 2.1
Rectangle {
width: 400;height: 400
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
}
}
函数和属性的使用:
输出项数:
Component.onCompleted: {
console.log(itemModel.count)
}
追加内容:
Rectangle{
id:rect1
height: 30;width: 80;color: "yellow"
}
Component.onCompleted: {
itemModel.append(rect1)
}
获取内容:
Component.onCompleted: {
console.log(itemModel.get(0).height)
console.log(itemModel.get(0).width)
console.log(itemModel.get(0).color)
}
其他的功能使用方法类似,就不介绍了