Skip to content
Advertisement

Limit Qlistview to 1 selected item at most

I try to compel the program to select the 1st item(and only it) in the QListview if user’s selection is more 1 and includes the 1st item. The selectionMode flag is multiselection, which means user can select several items in the listview.

Below is my code:

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;
    }

    //..
}

in the constructor:

connect
(selectedchannels,
  SIGNAL(selectionChanged(const QItemSelection &,const QItemSelection &)),
  this,
  SLOT(when_allchannel_selected(const QItemSelection &,const QItemSelection &)));

But this code does not work. It only deselects the last selection the user made before user selects 1st item instead of deselecting all other items except 1st item. How can I do this?

Additional questions:

  1. is the index in QItemSelection and QItemSelectionModel the same with the index in QStandardItemModel?

like if the index of 1st item in QStandardItemModel is 0, then if it’s been selected, no matter what the sequence is, the index will still be 0 in QItemSelection and QItemSelectionModel. (it seems that online material implies that they are the same..)

  1. it seems that the reset() method works. But why I can still see multiple selections in the ListView?

Advertisement

Answer

It turns out that I should use select() method of QItemSelectionModel rather than reset() method. Below is the code that works.

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;
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement