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
Here is the model I use:
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?
It is, of course, a context problem. In your code, the
name
,team
andtype
context properties inserted by theListView
intodelegate
's context is inaccessible to the components inside your delegates, as theLoader
uses the creation context ofcustomDelegate
anddefaultDelegate
as the parent context when instantiating them, andname
,team
andtype
do not refer to anything withing that context chain. One solution is to explicitly set the required information as a property of theLoader
(this works because theLoader
sets itself as the context object for the component it is loading).Following a working example:
For further reading and improvements I highly recommend you to read this.