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: 3model: [ "red", "yellow", "green" ]model: [ {color: "red"}, {color: "yellow"}, {color: "green"} ]model: ListModel{ ListElement{color: "red"}; ListElement{color: "green"} }- subclassed
QAbstractItemModeland 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
modelwhich is visible toRepeaterorInstantiator'sdelegatecontains everything that is visible to saiddelegateincludingindexandmodelData.Said
modelcan be used as a parameter toListModel.append()to create aListModelwith a single element.It can then be assigned as a
modelto aRepeaterwhich will load thedelegatewith a copy of all context properties that QML normally derives from the element ofView'smodelincludingindex,modelDataandmodelitself.Upon instantiation,
Repeater/InstantiatorfiresonItemAdded/onObjectAddedsignal, which can be used as a cue to obtain a reference to the instance ofView'sdelegateUser of the
Viewcan be asked to provide a rootpropertyin thedelegatethat would store obtained/calculated value which can be used by aViewAlternatively, the
Viewcan contain anotherRepeaterorInstantiatorand request anotherdelegateto obtain values it itself needs. Or a container type can encapsulate bothView's data and visualItem.Example:
MyView.qml
UsageExamples.qml