如何使用索引访问 ListView 中的委托属性 [英] How to access delegate properties in ListView using index
问题描述
我想访问 ListView
中的委托属性.我试过 contentItem
但有时它是 undefined
.
I want to access delegate properties in ListView
. I've tried with contentItem
but sometimes it's undefined
.
这是我的代码:
ListModel{
id: modeldata
ListElement{
name:"don"
rank:1
}
ListElement{
name:"shan"
rank:2
}
ListElement{
name:"james"
rank:3
}
ListElement{
name:"jeggu"
rank:4
}
}
Component{
id: delegateitem
Row {
property int count: rank
Rectangle{
width: 100
height: 50
Text{
anchors.centerIn: parent
text: name
}
}
}
}
ListView{
id: listview
focus: true
anchors.fill: parent
model: modeldata
delegate: delegateitem
onCurrentIndexChanged: {
console.log("position",currentIndex)
console.log("property",contentItem.children[currentIndex].count);
}
}
位置 1 处的问题无效输出
qml: position 0
qml: property 1
qml: position 1
qml: property undefined
qml: position 2
qml: property 2
qml: position 3
qml: property 3
推荐答案
首先:如果您尝试从列表外部访问列表元素,这是一个很好的指示,您应该重新考虑您的设计.
First of all: if you are trying to access list elements from outside your list, this is a good indicator that you should rethink your desing.
现在的解决方案是:一个列表视图有更多的孩子,而不仅仅是它的项目.例如,您可以通过定义属性属性字符串类型:myType""来过滤它们.然后通过循环遍历子项来查找项,并且只选取类型属性等于myType"的项.它有点像黑客,但同样,您一开始就不应该这样做.
Now the solution: a listview has more children than only its items. You can filter them out by defining a property "property string type: "myType" " for example. Then find the items by looping over the children and only take those where the type property equals "myType". Its somewhat of a hack but again you should really not be doing this in the first place.
这篇关于如何使用索引访问 ListView 中的委托属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!