将 Qlistview 限制为最多 1 个选定项目

Limit Qlistview to 1 selected item at most

本文关键字:项目 Qlistview      更新时间:2023-10-16

如果用户的选择更多为 1 并且包含第 1 项,我尝试强制程序在QListview中选择第 1 项(并且仅选择它)。选择模式标志是多选,这意味着用户可以在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 &)));

但是此代码不起作用。它仅取消选择用户在选择第 1 项之前所做的最后选择,而不是取消选择除第 1 项之外的所有其他项。我该怎么做?

其他问题:

  1. QItemSelectionQItemSelectionModel的索引是否与QStandardItemModel中的索引相同?

就像如果QStandardItemModel中第1项的索引是0,那么如果它被选中了,无论顺序是什么,索引仍然会在QItemSelectionQItemSelectionModel0。(似乎在线材料暗示它们是相同的..)

  1. 似乎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;
}