我尝试强制程序在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
中看到多个选项? 答案 0 :(得分:0)
事实证明我应该使用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;
}