rahul
rahul

Reputation: 406

Qt - SelectedItems in QTableView

I'm trying to return a vector of selected rows from a QTableView widget(snippet copied below), however the values returned do not correspond to the selection and I believe I've not understood QModelIndexList/QModelIndex with respect to QTableView. Can you let me know where I'm wrong or the right way to access selected items from a QTableView? C_model is of type QStandardItemModel

for(int i = 0; i < c_model->rowCount(); i++)
  {
    if (selectionModel->isRowSelected(i, QModelIndex()))
    {
      QStringList selection;
      std::vector<std::string> currentIndexValues;
      for (int j = 0; j < c_model->columnCount(); j++)
      {
        QVariant q = c_model->data(c_model->index(i, j));
        selection.append(q.toString());

        currentIndexValues.push_back(q.toString().toLocal8Bit().constData());
        printf(" %s\t ", currentIndexValues[j].c_str());
      }
      printf("\n");
      v_selectedItems.push_back(currentIndexValues);
    }
  }

Thanks

Upvotes: 3

Views: 3740

Answers (1)

Tim Meyer
Tim Meyer

Reputation: 12600

QAbstractItemView (the base class of QTableView) offers a QItemSelectionModel for this purpose. You can access that model via QTableView::itemSelectionModel() and then retrieve the selected rows via QItemSelectionModel::selectedRows():

QModelIndexList selectedRows = yourTableView->selectionModel()->selectedRows();

foreach( QModelIndex index, selectedRows )
{
    int row = index.row();
}

Upvotes: 5

Related Questions