Keeping selection consistent after InternalMove in QListView?
-
I have a QListView and underlying model all working well. It's set up to allow drag&drop InternalMoves, and allows selection of a single item. The only thing that I can't figure out is how to get the selection to update correctly after an InternalMove happens.
If I have three items in the list:
Item 1
Item 2
Item 3then I select Item 3
Item 1
Item 2
[Item 3] <- selectedand then drag it to be between items 1 and 2, the selection position stays the same - the third item of the list is selected, but because of the internal move, that item is now Item 2.
Item 1
Item 3
[Item 2] <- selectedI'm trying to figure out how to keep the selection on the item that was moved. Is this supposed to be handled automatically? I've tried looking at doing things like subclassing QListView and writing my own dropEvent handler, but it seems problematic. The DropEvent is generated before the internal move completes. Dropping the item inserts an item into the list, then after DropEvent is called and returns, the current selection is deleted. If I mess with the selection in dropEvent(), the wrong item will get deleted.
Any ideas?
-
Ok, figured it out. I used the rowsInserted and rowsRemoved signals generated by the model. rowsInserted saves the starting row number - this is the destination row of the drop. rowsRemoved sets the selection to the row number we saved in rowsInserted. The row number has to be adjusted by -1 if the destination row is greater than the source row to account for the deleted source row.
Doing this results in the correct item being selected after the drag&drop completes.
The only trick is that we need to be able to distinguish between row insertions and removals that are due to drag & drop, and insertions and removals from other sources. A simple flag set by the application when Add or Remove actions are initiated by the UI takes care of this.