Although I already figured it out, it took quite a while. If you know a less convoluted solution - please share.
I'd like to provide a custom View
that works with any type of model
(with arbitrarily named fields):
model: 3
model: [ "red", "yellow", "green" ]
model: [ {color: "red"}, {color: "yellow"}, {color: "green"} ]
model: ListModel{ ListElement{color: "red"}; ListElement{color: "green"} }
- subclassed
QAbstractItemModel
and such...
To do that I decided to provide a property Component delegate
that user would populate with a visual Item
that would be inserted deep into my View
.
However, the View
also needed to access some information from that same delegate
because otherwise it would either promote unneeded code duplication, or unneeded complexity of proxy model
.
MyView {
mymodel: ["red", "blue"]
mydelegate: Text {
text: "color=" + modelData.name
must_also_somehow_set_color_of_MyView_element_to: modelData.color
}
}
...where MyView should be something like:
Column {
Repeater {
model: mymodel
delegate: Rectangle {
color: somehow_get_color_from_mydelegate
Text {} // <--- instantiate mydelegate here with data from mymodel
}
}
}
Doing so seems easy but a naive attempts didn't work. The solution posted as an answer did for me.
The trick is that
model
which is visible toRepeater
orInstantiator
'sdelegate
contains everything that is visible to saiddelegate
includingindex
andmodelData
.Said
model
can be used as a parameter toListModel.append()
to create aListModel
with a single element.It can then be assigned as a
model
to aRepeater
which will load thedelegate
with a copy of all context properties that QML normally derives from the element ofView
'smodel
includingindex
,modelData
andmodel
itself.Upon instantiation,
Repeater
/Instantiator
firesonItemAdded
/onObjectAdded
signal, which can be used as a cue to obtain a reference to the instance ofView
'sdelegate
User of the
View
can be asked to provide a rootproperty
in thedelegate
that would store obtained/calculated value which can be used by aView
Alternatively, the
View
can contain anotherRepeater
orInstantiator
and request anotherdelegate
to obtain values it itself needs. Or a container type can encapsulate bothView
's data and visualItem
.Example:
MyView.qml
UsageExamples.qml