Qt's documentation seems a bit short on the issue, but I'm trying to use QLists as models for a ListView. The thing is, I'm representing a hierarchy, and whenever an item is clicked, the model is swapped with another one, which QML gets from a C++ callback.
This is the object representing a list item:
class MyObject : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ getName WRITE setName)
Q_PROPERTY(QString subtitle READ getSubtitle)
Q_PROPERTY(QList<QObject*> descent READ getChildren NOTIFY childrenUpdated)
...
}
And how I use it in QML:
ListView {
id: list_view
model: myModel
anchors.fill: parent
delegate: Item {
id: row
height: 50
anchors.left: parent.left
anchors.right: parent.right
MouseArea {
anchors.fill: row
onClicked: {
list_view.model = descent;
}
}
Column {
Text { text: name }
Text { text: subtitle }
}
}
}
The "myModel" model is set in the main, like this:
context->setContextProperty("myModel", QVariant::fromValue(folder.getChildren()));
The first time ListView appears, it uses myModel as a model, and it works. Whenever I click on an item, however, the ListView creates the exact number of items expected... but it cannot read any of their properties !
How come ListView knows exactly how much items it needs to create, yet cannot see their properties ?
I believe this is the correct behaviour you're observing. QML knows the number of elements in the QList
but as far as querying them for name
and subtitle
that's not possible because descent
doesn't conform to the constraints of ListView::model
From the QML documentation for the ListView::model property:
The model provides the set of data that is used to create the items in the view. Models can be created directly in QML using ListModel, XmlListModel or VisualItemModel, or provided by C++ model classes. If a C++ model class is used, it must be a subclass of QAbstractItemModel or a simple list.
So in that regard, you'll either have to change descent
to be a simple list which I believe means containing simple data such as a single QString
, int
, etc... or implement it as QAbstractItemModel
which contains your list of QObjects
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With