QML模型(VisualItemModel)

文章介绍了QML中的VisualItemModel和ObjectModel,VisualItemModel用于包含数据和委托的QML项目,而ObjectModel现更常用于替代它。ObjectModel提供count属性和append、clear等方法进行操作。示例展示了如何在ListView中使用这两个模型,并给出了添加、获取内容的代码片段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)
        }

其他的功能使用方法类似,就不介绍了 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值