Reputation: 593
I am using a custom model for my QML view and I want to be able to move items thanks to a drag and drop.
I use a list in my cpp model to set Data and then I just bind my model to the QML view
.
However, when I drop an item in a new position, the view ask the model to move the item on is new position.
In that purpose, I just update my dataList with the function dataList.move(oldIndexPosition, newIndexPosition)
.
My dataList is correctly updated but it doesn't refresh the QML view.
I tried to use the signal emit dataChanged()
but it is still not refreshing the view.
I don't understand what should I do, any suggestion ?
Here is a simple example of what I try to do. Notice that there is no drag and drop here, in order to make it easier to understand:
public:
Q_INVOKABLE void move(int oldIndex, int newIndex) {
dataList.move(oldIndex,newIndex);
emit dataChanged(this->index(oldIndex),this->index(newIndex));
}
signals:
void dataChanged(const QModelIndex & topLeft, const QModelIndex & bottomRight);
model.h
int main(int argc, char ** argv)
{
QGuiApplication app(argc, argv);
Model model;
model.addSomeData("data1");
model.addSomeData("data2");
model.addSomeData("data3");
QQuickView view;
view.setResizeMode(QQuickView::SizeRootObjectToView);
QQmlContext *ctxt = view.rootContext();
ctxt->setContextProperty("myModel", &model);
view.setSource(QUrl("qrc:view.qml"));
view.show();
return app.exec();
}
main.cpp
ListView {
width: 200; height: 250
model: myModel
delegate: Text { text: "data " + data }
MouseArea {
anchors.fill: parent
cursorShape: Qt.PointingHandCursor
onClicked: {
myModel.move(0,2) //Just a test
}
}
}
myqml.qml
If you have any idea of what I am doing wrong, that would be really kind of you to help me! Thank you very much.
Upvotes: 1
Views: 1505
Reputation: 11054
I assume Model
is an implementation of QAbstractItemModel
. In that case, you should call QAbstractItemModel::beginMoveRows
before you start moving your data and QAbstractItemModel::endMoveRows
to finalise it.
Q_INVOKABLE void move(int oldIndex, int newIndex) {
QModelIndex parent;
beginMoveRows(parent, oldIndex, oldIndex, parent, newIndex);
dataList.move(oldIndex,newIndex);
endMoveRows();
}
Upvotes: 4