I have a QML Repeater on a Grid, when I click on an item, I emit a signal which is processed by a C++ class. Then, I change an array in C++ which is then assigned as a model of the QML Repeater.
Is there a way to change just two elements of the C++ model, not the whole model as I did?
QML code:
Grid{
height:width
rows:8
columns: 8
Repeater{
id: chessPiecesRptr
...
signal chessfigureSelected(int index)
delegate: Item{
id:chessPiecesItm
Image{
...
}
MouseArea
{
anchors.fill:parent
onClicked: {
chessPiecesRptr.chessfigureSelected(index)
}
}
}
}
}
The C++ method which updates the Repeater's model:
void ChessFiguresClass::changeModel()
{
QStringList dataList;
for(int i=0;i<64;i++)
dataList.append(QChar(posArray[i]));
QQmlProperty::write(chessPiecesRptr, "model", QVariant::fromValue(dataList));
}
Contrary to the accepted answer it is indeed possible without going all the way to implement an entire QAbstractListModel.
It is true that QStringList doesn't have any way to notify for changes, but all you have to do is wrap it up in a property, something like this:
Q_PROPERTY(QVariant myModel READ myModel NOTIFY myModelChanged)
...
QVariant myModel() { return QVariant::fromValue(myStringList); }
...
void myModelChanged(); // signal
And just emit myModelChanged every time you want to reflect a change in the model, be that replacing it with a different model or changing it internally. And use the myModel property for the Repeater's model.
However, if you have a lot of items in the model or the delegates are complex, it is always a good idea to implement your own QAbstractListModel, because with the approach above, the repeater will recreate the entire model every time it "changes", whereas the QAbstractListModel will only update the actual changes.
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