Switching/moving rows in a model
Hello,
I'm trying to implement "move up" and "move down" for items in my model. I'm not using a QSortFilterProxyModel and I won't.
Is there a working way to do this?
From my understanding what the docs tell me, I would have to exchange the first row index with the second one and vice versa. But it won't work.
Code:
emit layoutAboutToBeChanged();
changePersistentIndex(from, to); // This call overwrites and does not exchange?
changePersistentIndex(to, from);
emit layoutChanged();
Thanks.
Re: Switching/moving rows in a model
try something like this
Code:
bool Model
::moveItem(const QModelIndex &fromParent,
int fromRow,
{
...
changePersistentIndex(pCurrent, index(toRow, 0, toParent));
if (up)
removeRows(fromRow + 1, 1, fromParent);
else
removeRows(fromRow, 1, fromParent);
...
}
Re: Switching/moving rows in a model
Actually what you need to do is remove the second row and insert it before the first one.
Here is some pseudocode
Code:
QVariantMap item = secondIndex.itemData();
removeRow(secondIndex.row(), secondIndex.parent());
insertRow(firstIndex.row(), firstIndex.parent());
setItemData(index(firstIndex.row(), 0), item);
Re: Switching/moving rows in a model
Quote:
Originally Posted by
wysota
Actually what you need to do is remove the second row and insert it before the first one.
Here is some pseudocode
Code:
QVariantMap item = secondIndex.itemData();
removeRow(secondIndex.row(), secondIndex.parent());
insertRow(firstIndex.row(), firstIndex.parent());
setItemData(index(firstIndex.row(), 0), item);
I'm sure this would work, but if my selection model's currentIndex() points to the secondIndex, the selection would be gone :(
I need a solution that does not just work with up/down, it should support exchanging the last with the first item for example..
Re: Switching/moving rows in a model
So simply exchange data from both items and emit dataChanged for both of them. Just be aware this is not exchanging rows but exchanging their values. If you have a persistant index pointing to both of them, they will not be exchanged and will be pointing to wrong indexes after the swap. With "my" approach you at least save one of them.