QTableView - 限制所选项目的数量? [英] QTableView - Limit number of selected items?

查看:61
本文介绍了QTableView - 限制所选项目的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题在标题中.没有函数 QTableView::set_Max_Number_SelectedItems( int ).

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

当所选项目的数量为2时,我想禁用物品的选择.

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

谢谢

推荐答案

您可以禁用选择:

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

我在这里使用了 C++11(CONFIG += c++11.pro 文件)和 信号和槽的新语法,当然如果你愿意,你可以使用旧语法.

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.

但在这种情况下,此用户将根本无法使用选择.如果这是你想要的,那就没问题了.如果没有,那么您可以启用选择,例如当 tableView 失去焦点或为此提供特殊按钮时.

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

它有什么作用?当用户尝试选择超过 2 个项目时,最后选择的项目取消选择并且用户根本不能选择超过 2 个项目,只能选择最后选择的 + 当前选择的项目.我不知道你的任务的规格,所以选择最合适的方法.

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.

这篇关于QTableView - 限制所选项目的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆