Implementing Drag and Drop with QTreeView

Viewed 9039

I am trying to implement drag and drop for a TreeView using a model based off of QAbstractItemModel, taken from this example.

As instructed here I have enabled my TreeView for drag&drop like so:

view->setDragDropMode(QAbstractItemView::InternalMove);
view->setSelectionMode(QAbstractItemView::ExtendedSelection);
view->setDragEnabled(true);
view->setAcceptDrops(true);
view->setDropIndicatorShown(true);

I have set the appropriate flags in my model as well:

Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return 0;

    return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | Qt::ItemIsEditable | QAbstractItemModel::flags(index);
}

And reimplemented QAbstractItemModel::supportedDropActions()

Qt::DropActions TreeModel::supportedDropActions() const
{
    return Qt::CopyAction | Qt::MoveAction;
}

The result is that when I drop one row on top of another, the latter gets a new child row and the original row is not deleted. However, all I want is to be able to switch the ordering of my top-level rows.

Perhaps my model is unsuitable? I have found this article in the documentation, but it seems more complex than what I need.

Edit: I have now implemented DropMimeData() as follow, still no luck though.

bool TreeModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent){

    if(!canDropMimeData(data, action, row, column, parent))
            return false;

    if (action == Qt::IgnoreAction)
        return true;

    int beginRow;

    if (row != -1)
        beginRow = row;
    else if (parent.isValid())
        beginRow = parent.row();
    else
        beginRow = rowCount(QModelIndex());

    removeRow(row, parent);
    insertRow(beginRow, parent);
    setData(parent.child(beginRow, 0), data);

    return true;

}
0 Answers
Related