问题描述
我正在尝试学习如何在 Qt 中实现拖放以实现模型/视图设置。作为练习,我尝试对 Qt 网站上提供的 Editable Tree Model example 执行此操作:
为了使用拖放对其进行扩展,我按照 Qt 文档中关于 "Using Drag and Drop with View Items" 的说明进行操作,更具体地说是 "Using model/view classes"。
我将尝试的代码放在 a GitHub repository。主要修改如下,但还有其他重要的修改; here are the full changes 根据文档。
/* mainwindow.cpp -- THIS IS NOT ALL CHANGES -- See link above for all changes */
view->setSelectionMode(QAbstractItemView::SingleSelection);
view->setDragEnabled(true);
view->viewport()->setAcceptDrops(true);
view->setDropIndicatorShown(true);
view->setDragDropMode(QAbstractItemView::DragDrop);
然而,这并没有完全奏效。虽然我可以拖放项目,但复制的项目显示为空白。这可以在 this screen capture 中看到,但主要截图是:
请注意,文档描述了需要重新实现 qabstractitemmodel
的 dropMimeData
以实现拖放功能,而我没有这样做。这是因为,在检查 source code for that class 时,我发现 its default implementation 应该已经可以在拖放中复制项目,因为它 uses the default application/x-qabstractitemmodeldatalist
MIME 格式和 {{3 }} 用于插入的项目。
这里有什么问题?是默认的 dropMimeData
不起作用,还是其他原因?
解决方法
示例提供的模型只接受角色为 Qt::EditRole
的设置数据。请参阅 treemodel.cpp
bool TreeModel::setData(const QModelIndex &index,const QVariant &value,int role)
{
if (role != Qt::EditRole)
return false;
...
}
删除该部分或添加Qt::DisplayRole
,数据将被正确设置。