使用QTreeView实现拖放

时间:2017-08-10 17:03:02

标签: c++ qt drag-and-drop treeview

我正在尝试使用基于QAbstractItemModel的模型实现对TreeView的拖放,取自this example

按照说明here我已经启用了TreeView以进行拖放操作:

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

我也在我的模型中设置了适当的标志:

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

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

并重新实现了QAbstractItemModel :: supportedDropActions()

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

结果是当我将一行放在另一行之上时,后者获得一个新的子行并且不删除原始行。但是,我想要的是能够切换顶级行的顺序。

也许我的model不合适?我在文档中找到了this article,但它似乎比我需要的更复杂。

编辑:我现在已经实施了DropMimeData(),但仍然没有运气。

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 个答案:

没有答案
相关问题