简体   繁体   English

Qt:尝试将拖放添加到可编辑树 Model 示例不起作用

[英]Qt: Attempt to add Drag and Drop to Editable Tree Model example not working

I'm trying to learn how to implement Drag and Drop to model/view settings in Qt.我正在尝试学习如何在 Qt 中实现拖放到模型/视图设置。 As an exercise, I attempted to do that to the Editable Tree Model example available at the Qt web site:作为练习,我尝试对 Qt web 站点上的可编辑树 Model 示例执行此操作:

可编辑树模型

To extend it with Drag and Drop, I followed the instructions in Qt's documentation on "Using Drag and Drop with View Items" , more specifically "Using model/view classes" .为了通过拖放扩展它,我按照 Qt 文档中关于“使用拖放查看项目”中的说明进行操作,更具体地说是“使用模型/视图类”

I placed the code for my attempt at a GitHub repository .我将尝试的代码放在GitHub 存储库中。 The main modifications are below but there are other important ones;主要修改如下,但还有其他重要修改; here are the full changes according to the documentation. 这是根据文档的完整更改

/* 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);

However, this didn't quite work.然而,这并不完全奏效。 While I can drag and drop items, the copied item appears as blank.虽然我可以拖放项目,但复制的项目显示为空白。 This can be seen in this screen capture , but the main screenshots are:这可以在此屏幕截图中看到,但主要屏幕截图是:

将“开始”拖到“编写对话框”上

结果为空白项

Note that the documentation describes the need to re-implement QAbstractItemModel 's dropMimeData for drag and drop functionality, which I did not.请注意,文档描述了需要重新实现QAbstractItemModeldropMimeData以实现拖放功能,而我没有这样做。 This is because, upon inspecting the source code for that class , I find that its default implementation should already work in copying items in drag and drop, since it uses the default application/x-qabstractitemmodeldatalist MIME format and uses setItemData for the inserted items.这是因为,在检查该class 的源代码时,我发现它的默认实现应该已经在拖放复制项目中起作用,因为它使用默认的application/x-qabstractitemmodeldatalist MIME 格式并使用setItemData插入的项目。

What is wrong here?这里有什么问题? Is it the default dropMimeData that's not working, or something else?是默认的dropMimeData不起作用还是其他原因?

The model provided by the example only accepts setting data with role Qt::EditRole .示例提供的 model 只接受角色Qt::EditRole的设置数据。 See line 263 in treemodel.cpp请参阅treemodel.cpp中的第 263 行

bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (role != Qt::EditRole)
        return false;

    ...
}

Removing that part or adding Qt::DisplayRole and the data will be set properly.删除该部分或添加Qt::DisplayRole并且数据将正确设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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