在使用QStandardItemModel作为其模型的QListView中,如何防止重复?数据是通过拖放添加的,所以我尝试覆盖QStandardItemModel::dropMimeData,这似乎有些奇怪,因为我还需要覆盖QStandardItemModel::mimeData (并重新实现encodeData/decodeData)。这必须更简单些!
发布于 2011-04-01 15:52:01
嗯,我设法通过覆盖QListView::dataChanged来解决这个问题,它在删除Qt::DisplayRole之后检查模型中是否有多个项目具有相同的数据,如果有,则删除其中一个。基本上看起来是这样的:
void MyListView::dataChanged(QModelIndex topLeft, QModelIndex bottomRight)
{
// there can be only one item dragged at once in my use case
if(topLeft == bottomRight)
{
QStandardItemModel* m = static_cast<QStandardItemModel*>(model());
// if theres already another item with the same DisplayRole...
if(m->findItems(topLeft.data().toString()).count() > 1)
{
// ... we get rid of it.
model()->removeRow(topLeft.row());
}
}
else
{
// let QListView decide
QListView::dataChanged(topLeft, bottomRight);
}
}到目前为止,它并不完美(例如,如果你可以一次丢弃多个项目),但它适用于这个简单的用例。
发布于 2011-03-07 10:22:05
我能看到的最简单的方法是创建你自己的代理模型。
请参阅http://doc.qt.io/qt-5/qabstractproxymodel.html
https://stackoverflow.com/questions/5214249
复制相似问题