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的數量即可.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章