c++ - 阻止 QListView 删除拖放条目

标签 c++ qt qt5 qlistview

我创建了一个带有 QStringListModel 的 QListView。

listModel = new QStringListModel(ui->listView);
ui->listView->setModel(listModel);
ui->listView->setEditTriggers(QListView::NoEditTriggers);
ui->listView->setDragDropMode(QListView::InternalMove);

然后我使用以下方式添加项目:

void MainWindow::addItem(QString result)
{
    if (result == "")
        return;
    listModel->insertRow(listModel->rowCount());
    QModelIndex a = listModel->index(listModel->rowCount()-1);
    listModel->setData(a,result);
}

问题是,当您在列表中拖动一个项目并尝试将其移动到另一个位置时,它更愿意覆盖您将其拖动到的项目。我不希望通过拖放操作删除项目。

最佳答案

从文档中我们得到了一些关于在 QListView::dragDropOverwriteMode 中寻找控制覆盖行为的位置的提示。 :

Note: This is not intended to prevent overwriting of items. The model's implementation of flags() should do that by not returning Qt::ItemIsDropEnabled.

这告诉我们模型是控制它的模型。然后查看 QStringListModel::flags(const QModelIndex & index) const 的文档我们可以看到它默认启用覆盖:

Reimplemented from QAbstractItemModel::flags(). Returns the flags for the item with the given index. Valid items are enabled, selectable, editable, drag enabled and drop enabled.

因此,为了更改此行为,您需要自定义模型(即至少从 QStringListModel 派生)并将 flags(const QModelIndex & index) const 方法的行为更改为不返回Qt::ItemIsDropEnabled

这应该会阻止您的条目被覆盖。

关于c++ - 阻止 QListView 删除拖放条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21821106/

相关文章:

具有大量 Windows 或复杂 UI 的 Qt 5 QML 应用程序

Qt:在QML中通过ID任意访问元素

c++ - 如何优化for循环?

c++ - Qt中文本的定位规则到底是什么?

c++ - Xcode 中的缩进错误

c++ - 为什么 Kdevelop 4 在项目中两次显示我的源 cpp 文件?

c++ - Qt 代码编辑器在右侧区域显示行号

c++ - 访问 QApplication::arguments 时出现段错误

c++ - 2 我的 strcmp 函数测试失败

c++ - 将 stringstream 换成 cout