QTableView - Limit number of selected items?

♀尐吖头ヾ 提交于 2019-12-11 03:21:39

问题


The question is in the title. There is no function QTableView::set_Max_Number_SelectedItems( int ).

When the number of selected items is 2, I want to disable selection of item.

Thanks


回答1:


You can disable selection with this:

connect(ui->tableView->selectionModel(),&QItemSelectionModel::selectionChanged,[=]() {//with lambda
    if(ui->tableView->selectionModel()->selectedIndexes().size() > 1)
        ui->tableView->setSelectionMode(QAbstractItemView::NoSelection);
});

I used here C++11 (CONFIG += c++11 to .pro file) and new syntax of signals and slots, but of course you can use old syntax if you want.

But in this case after this user will not be able to use selection at all. If it is what you want, then it's fine. If no, then you can enable selection for example when tableView loses focus or provide special button for this.

But I also think that next code is more suitable for you:

connect(ui->tableView->selectionModel(),&QItemSelectionModel::selectionChanged,[=]() {//with lambda
    if(ui->tableView->selectionModel()->selectedIndexes().size() > 2)
    {
        QList<QModelIndex> lst = ui->tableView->selectionModel()->selectedIndexes();
        ui->tableView->selectionModel()->select(lst.first(),QItemSelectionModel::Deselect);
    }
});

What it does? When user try to select more than 2 items, last selected item deselect and user can't select more than 2 items at all, only last selected + currently selected. I don't know specification of your task, so choose the most suitable approach.



来源:https://stackoverflow.com/questions/27272543/qtableview-limit-number-of-selected-items

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!