问题
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