Frage

I have created a QListView with a QStringListModel.

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

And I add items using:

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

The problem is, when you drag an item in the list and try to move it to another position, it prefers to over-write the item you drag it to. I do not ever want an item to be deleted by a drag-drop action.

War es hilfreich?

Lösung

From the documentation we get a bit of a hint of where to look for controlling overwrite behaviour in 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.

This tells us the model is the one that controls it. Then looking at the documentation for QStringListModel::flags(const QModelIndex & index) const we can see it does enable overwrite by default:

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.

So in order to change this behaviour you will need to customize your model (i.e. derive from QStringListModel at minimum) and change the behaviour of the flags(const QModelIndex & index) const method to not return Qt::ItemIsDropEnabled.

That should stop your entry from getting overwritten.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top