Details
-
Bug
-
Resolution: Done
-
P3: Somewhat important
-
4.7.1
-
None
-
25e3227fc922f75cc772aadb9dd07cc8b965dcbd
Description
Based on discussion on #qt-irc: in some cases it is very useful to access the view and/or model from a delegate. How to do this is not explained in docs.
I would suggest that corresponding explanation should be done at the end of: doc/src/declarative/qdeclarativemodels.qdoc
I attach a patch with a sketch of how I would describe this:
\section1 Accessing View and Model from Delegate You can access the view for which a delegate is used, and its properties, by ListView.view in a delegate on a ListView, GridView.view in a delegate on a GridView etc. In particular, you can access the model (and its properties) by ListView.view.model. This can be useful, for example, if you want to use the same delegate for a number of views, but you want decorations or other features to be different for each view and you would like these different settings to be properties of each of the views. Similarly it might be of interest to access or show some properties of the model (for example, a parameter based on which a query was executed etc.). In the following example delegate shows property "language" of the model, and color of one of the fields depends on a property "fruit_color" of the view. \code Rectangle { width: 200; height: 200 ListModel { id: fruitModel property string language: "en" ListElement { name: "Apple" cost: 2.45 } ListElement { name: "Orange" cost: 3.25 } ListElement { name: "Banana" cost: 1.95 } } Component { id: fruitDelegate Row { Text { text: " Fruit: " + name; color: ListView.view.fruit_color } Text { text: " Cost: $" + cost } Text { text: " Language: " + ListView.view.model.language } } } ListView { property color fruit_color: "green" model: fruitModel delegate: fruitDelegate anchors.fill: parent } } \endcode Another important case is when some action (e.g. mouse click) in the delegate should update data in the model. In such a case you can, for example, define in the model a function setData(int row, const QString & field_name, QVariant new_value), and call it from the delegate using ListView.view.model.setData(index, field, value), provided "field" holds the name of the field which should be updated and "value" the new value.