简体   繁体   中英

qtreeview: drag and drop of a subtree results in bad selections

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();
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM