I've been trying to drag and drop a subtree in qtreeview. The tree correctly re-orders when I execute the drop and the underlying model is updated, however, item selection is then screwed up afterwords. I haven't been able to come up with a reliable way to force QT to redraw the selection appropriately. See screenshots below:
Before:
After dragging the top node to node 2:
Relevant view code:
void View::dropEvent(QDropEvent *evt)
{
QTreeView::dropEvent(evt);
QModelIndex start = indexAt(_drag_start);
QModelIndex end = indexAt(evt->pos());
_model->moveTo(start, end);
}
Relevant Model code:
void Model::moveTo(QModelIndex& start, QModelIndex& end)
{
// ... omitted some error checking code to ensure start and end have the same parent
ModelData* a = (ModelData*) start.internalPointer();
ModelData* b = (ModelData*) end.internalPointer();
ModelData* list = (ModelData*) (parent(start).internalPointer());
int idxa = list->indexOf(a);
int idxb = list->indexOf(b);
// underneath this is QList<...>::moveTo
list->moveTo( idxa, idxb );
QModelIndex p = this->parent(start);
emit dataChanged( index(0, 0, p), index(rowCount(p)-1, 1, p) );
}
Any suggestions? Thanks!
Turns out this is fixed by adding the following code in the Model::moveTo() method:
...
emit layoutAboutToBeChanged();
list->moveTo( ... );
emit layoutChanged();
...