PDA

View Full Version : Switching/moving rows in a model



gri
11th December 2008, 13:15
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.


emit layoutAboutToBeChanged();

QModelIndex from = ...;
QModelIndex to = ...;

changePersistentIndex(from, to); // This call overwrites and does not exchange?
changePersistentIndex(to, from);

emit layoutChanged();


Thanks.

spirit
11th December 2008, 13:59
try something like this


bool Model::moveItem(const QModelIndex &fromParent, int fromRow,
const QModelIndex &toParent, int toRow, bool up)
{
...
QModelIndex to = index(toRow, 0, toParent);
QModelIndex from = index(fromRow, 0, fromParent);

QPersistentModelIndex pCurrent = from;

changePersistentIndex(pCurrent, index(toRow, 0, toParent));

if (up)
removeRows(fromRow + 1, 1, fromParent);
else
removeRows(fromRow, 1, fromParent);
...
}

wysota
11th December 2008, 14:06
Actually what you need to do is remove the second row and insert it before the first one.

Here is some pseudocode

QVariantMap item = secondIndex.itemData();
removeRow(secondIndex.row(), secondIndex.parent());
insertRow(firstIndex.row(), firstIndex.parent());
setItemData(index(firstIndex.row(), 0), item);

gri
17th December 2008, 11:09
Actually what you need to do is remove the second row and insert it before the first one.

Here is some pseudocode

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..

wysota
17th December 2008, 11:21
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.