代碼
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的數量即可.