From ea2130691ac7ea2a6d8c97f5c3be91c8f7a7fefd Mon Sep 17 00:00:00 2001 From: Aleksey Kontsevich Date: Wed, 29 Apr 2020 08:45:57 +0300 Subject: [PATCH] Allow to move/reorder objects within QmlObjectListModel --- src/QmlControls/QmlObjectListModel.cc | 16 ++++++++++++++++ src/QmlControls/QmlObjectListModel.h | 3 +++ 2 files changed, 19 insertions(+) diff --git a/src/QmlControls/QmlObjectListModel.cc b/src/QmlControls/QmlObjectListModel.cc index 50c3c123a..a9222c686 100644 --- a/src/QmlControls/QmlObjectListModel.cc +++ b/src/QmlControls/QmlObjectListModel.cc @@ -125,6 +125,22 @@ bool QmlObjectListModel::removeRows(int position, int rows, const QModelIndex& p return true; } +void QmlObjectListModel::move(int from, int to) +{ + if(0 <= from && from < count() && 0 <= to && to < count() && from != to) { + // Workaround to allow move item to the bottom. Done according to + // beginMoveRows() documentation and implementation specificity: + // https://doc.qt.io/qt-5/qabstractitemmodel.html#beginMoveRows + // (see 3rd picture explanation there) + if(from == to - 1) { + to = from++; + } + beginMoveRows(QModelIndex(), from, from, QModelIndex(), to); + _objectList.move(from, to); + endMoveRows(); + } +} + QObject* QmlObjectListModel::operator[](int index) { if (index < 0 || index >= _objectList.count()) { diff --git a/src/QmlControls/QmlObjectListModel.h b/src/QmlControls/QmlObjectListModel.h index e5b6b31c4..db7f7f1fa 100644 --- a/src/QmlControls/QmlObjectListModel.h +++ b/src/QmlControls/QmlObjectListModel.h @@ -46,6 +46,9 @@ public: bool contains (QObject* object) { return _objectList.indexOf(object) != -1; } int indexOf (QObject* object) { return _objectList.indexOf(object); } + /// Moves an item to a new position + void move(int from, int to); + QObject* operator[] (int i); const QObject* operator[] (int i) const; template T value (int index) { return qobject_cast(_objectList[index]); } -- 2.22.0