Qt tableView返回选中的行数

代码

void MainWindow::updateSelectionPeople(const QItemSelection &selected, const QItemSelection &deselected)
{
    QItemSelectionModel *model = ui->tableShowStudent->selectionModel();
    QItemSelection range = model->selection();
    QModelIndexList items = range.indexes();
    QMap<int,int>map;
    foreach (QModelIndex item, items) {
        map.insert(item.row(),0);
    }
    ui->label_selectCount->setText(QString::number(map.keys().count()));
}

model的选择模型

model不仅有数据模型,也有选择模型,负责选中和取消选中的任务

  • tableview必须setmodel()之后才会会选择模型,如果tableview没有setmodel(),此时返回选择模型则是一个null,无法连接信号槽
  • 正确的做法是,setmodel之后然后关联信号槽connect(ui->tableShowStudent->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(updateSelectionPeople(QItemSelection,QItemSelection)));
  • 每次更换model的时候,选择模型也会进行自动更换.
  • 上面的代码没有用参数,而是直接返回了model的选择范围,然后插入map,并且获得keys的数量即可.

猜你喜欢

转载自blog.csdn.net/wayrboy/article/details/84675442
QT
今日推荐