我创建了一个带有 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/