如果用户的选择多于 1 并且包括第一项,我会尝试强制程序选择 QListview
中的第一项(并且只有它)。 selectionMode 标志是多选,这意味着用户可以在 listview
中选择多个项目。
下面是我的代码:
void RealPlay::when_allchannel_selected
(const QItemSelection &selected,
const QItemSelection &deselected)
{
// if the selected is the same with deseleted then
// just return, this is not necessary
QModelIndexList selectedlist = selected.indexes();
for(int i =0 ; i < selectedlist.length();++i)
{
if(!deselected.contains(selectedlist.at(i)))
{
break;
}
return;
}
// channelmodel QStandardItemModel
// selectedchannels QItemSelectionModel
// ui->listView_channel QListView
//this is the first item that I want to select
QModelIndex firstiteminchannelview =
channelmodel->indexFromItem(channelmodel->item(0));
if(selectedchannels->isSelected(firstiteminchannelview)
&& (selectedchannels->selectedIndexes().length()>1))
{
selectedchannels->reset();
selectedchannels->select(firstiteminchannelview,\
QItemSelectionModel::Select);
//return;
}
//..
}
在构造函数中:
connect
(selectedchannels,
SIGNAL(selectionChanged(const QItemSelection &,const QItemSelection &)),
this,
SLOT(when_allchannel_selected(const QItemSelection &,const QItemSelection &)));
但是这段代码不起作用。它只取消选择用户在选择第一项之前所做的最后选择,而不是取消选择除第一项以外的所有其他项目。我该怎么做?
其他问题:
QItemSelection
和QItemSelectionModel
中的索引是否与QStandardItemModel
中的索引相同?
比如如果 QStandardItemModel
中第一项的索引是 0
,那么如果它被选中,无论序列是什么,索引仍然是 0
在 QItemSelection
和 QItemSelectionModel
中。 (好像网上的资料暗示他们是一样的..)
reset()
方法似乎有效。但为什么我仍然可以在ListView
中看到多个选择?
最佳答案
事实证明我应该使用 QItemSelectionModel 的 select() 方法而不是 reset() 方法。以下是有效的代码。
if(selectedchannels->isSelected(firstiteminchannelview) && (selectedchannels->selectedIndexes().length()>1))
{
//selectedchannels->reset();
QModelIndex top = channelmodel->index(1,0);
QModelIndex bottom = channelmodel->index(channelmodel->rowCount()-1,0);
QItemSelection selection(top, bottom);
selectedchannels->select(selection,QItemSelectionModel::Deselect);
selectedchannels->select(firstiteminchannelview,QItemSelectionModel::Select);
//return;
}
关于c++ - 将 Qlistview 限制为最多 1 个选定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34981289/