根据属性选择代理 [英] selecting delegates depending on property
问题描述
我有一个listview,我想使用defaultDelegate或customDelegate取决于一个属性的值。
到目前为止,我已经尝试使用一个组件来加载不同的代理:
I have a listview where I want to use either a defaultDelegate or a customDelegate depending on the value of a property. So far I've tried using a component to load the different delegates:
Component{
id: delegate
Loader {
sourceComponent: type == 3 ? customDelegate : defaultDelegate
}
}
但是,我无法访问我在我的模型中有两个代表的财产。我有以下错误:
However, I can't access the properties I have in my model from the two delegates I have. I have the following error:
ReferenceError: name is not defined
这是我使用的模型:
ListModel {
id: test
ListElement {
name: "Bill"
team: "554"
type: 2
}
ListElement {
name: "John"
team: "555"
type: 3
}
ListElement {
name: "Sam"
team: "556"
type: 1
}
}
有没有人有任何想法,我在这里做错什么?
Does anyone Have any idea, what I am doing wrong here?
推荐答案
当然是一个上下文问题。在您的代码中,名称
,团队
和类型
上下文由 ListView
插入到委托
的上下文中的属性无法访问代理中的组件,因为 Loader
使用 customDelegate
和 defaultDelegate
作为父上下文的创建上下文实例化它们,并且名称
,团队
和类型
不要请参考任何带有上下文链的内容。
一个解决方案是明确地将所需信息设置为 Loader
的属性(这是因为 Loader
将自己设置为正在加载的组件的上下文对象)
It is, of course, a context problem. In your code, the name
, team
and type
context properties inserted by the ListView
into delegate
's context is inaccessible to the components inside your delegates, as the Loader
uses the creation context of customDelegate
and defaultDelegate
as the parent context when instantiating them, and name
, team
and type
do not refer to anything withing that context chain.
One solution is to explicitly set the required information as a property of the Loader
(this works because the Loader
sets itself as the context object for the component it is loading).
遵循一个工作示例:
ListModel {
id: testModel
ListElement {
name: "Bill"
team: "554"
type: 2
}
ListElement {
name: "John"
team: "555"
type: 3
}
ListElement {
name: "Sam"
team: "556"
type: 1
}
}
ListView {
anchors.fill: parent
model: testModel
delegate: myDelegate
}
Component {
id: myDelegate // yourDelegate
Loader {
property string modelName: model.name
property string modelTeam: model.team
property int modelType: model.type
sourceComponent: modelType === 3 ? colonDelegate : semicolonDelegate
}
}
Component {
id: colonDelegate
Text { text: modelName + ": " + modelTeam }
}
Component {
id: semicolonDelegate
Text { text: modelName + "; " + modelTeam }
}
为了进一步阅读和改进,我强烈建议您阅读这个。
For further reading and improvements I highly recommend you to read this.
这篇关于根据属性选择代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!