Why does `required` change the value of a property?
-
I'm learning this example https://doc.qt.io/qtforpython-6/examples/example_quick_models_objectlistmodel.html#example-quick-models-objectlistmodel.
I made a small change to the example: the delegate was implemented in a separate QML. Then the code stopped working. After some trials, I found it was because the property was declared as
required
. Why doesrequired
change the value of a property? Thanks very much.// view.qml import QtQuick ListView { width: 100; height: 100 delegate: MyItem { mdl: model } } // MyItem.qml import QtQuick Rectangle { property var mdl // adding `required` will make mdl undefined color: mdl.modelData.color height: 25 width: 100 Text { text: mdl.modelData.name } }
The python file is the same as the example.
-
and do fix it you should do:
delegate: MyItem { required property var model mdl: model }
(or rename
mdl
tomodel
in MyItem.qml) -
Strange but true: by using "required" in a delegate, you basically opt in a different mode of operation.
See this section of the documentation for details: https://doc.qt.io/qt-6/qtquick-modelviewsdata-modelview.html#models
Especially note this paragraph from the documentation: "The model, index, and modelData roles are not accessible if the delegate contains required properties, unless it has also required properties with matching names."
This is what happens in your example: "model" is undefined and so "mdl" becomes undefined.
-
and do fix it you should do:
delegate: MyItem { required property var model mdl: model }
(or rename
mdl
tomodel
in MyItem.qml) -