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<QStandardItem*>(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();
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值