Qt listview 采用自定义model选择时会选择多个item的问题解决

具体的应用场景是有一个项目,采用Qt的listview来显示一个文件列表,

class FilelistModel : public QStandardItemModel
class ItemDelegate : public QItemDelegate
filelistModel = new FilelistModel(this);
ui->Lst_0015_browsing_list->setItemDelegate(delegate);
ui->Lst_0015_browsing_list->setModel(filelistModel);

model的2个关键函数:
Qt::ItemFlags FilelistModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
return Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled;
}
QVariant FilelistModel::data(const QModelIndex &index, int role) const
{
if ((index.row() < 0) || (index.column() < 0) || (index.model() != this)) {
return QVariant();
}
QStandardItem *parent = static_cast(index.internalPointer());
if (parent == 0) {
return QVariant();
}
QStandardItem *item = parent->child(index.row(), index.column());
if (item == NULL) {
return QVariant();
}
if (role == Qt::DisplayRole) {
return item->text();
} else if (role == Qt::DecorationRole) {
return item->data(FilelistModel::IconPath);
} else if (role == FilelistModel::Path) {
return item->data(FilelistModel::Path);
} else if (role == Qt::SizeHintRole) {
return QSize(550, 60);
} else if (role == FilelistModel::Type) {
return item->data(FilelistModel::Type);
}
if (Qt::CheckStateRole == role) {
// LANG_KIND kind = PalangOrder[index.row() % PA_LANG_END].kind;
if (index.row() == m_checked_item) {
return Qt::Checked;
} else {
return Qt::Unchecked;
}
}
return QVariant();
}

由于上面flag函数中设置了Qt::ItemIsSelectable,所以选择的时候会存在多项选择的问题,但我们的项目是不需要多项选择的,只允许选择一项。
查了Qt的资料,看到有这个函数:
void QAbstractItemView::reset() [virtual slot]

Reset the internal state of the view.

Warning: This function will reset open editors, scroll bar positions, selections, etc. Existing changes will not be committed. If you would like to save your changes when resetting the view, you can reimplement this function, commit your changes, and then call the superclass’ implementation.

原来调用这个方法就可以清除多选项,于是在itemclicked里面修改:
void FileList::itemClicked(QModelIndex index)
{
.....
ui->Lst_0015_browsing_list->reset();
}

你可能感兴趣的:(Qt)