60

After watching many threads about getting selected rows numbers, I am really confused.

How do you get ROW numbers in QTableView using QStandardItemModel I used below selection model and behavior as

setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::SingleSelection);

and if you have your own way of selecting can you explain how it works. Thanks for the help!

Angie Quijano
  • 4,167
  • 3
  • 25
  • 30
shett73
  • 601
  • 1
  • 5
  • 4

4 Answers4

76

The method selectionModel() return a QItemSelectionModel.

You can use QItemSelectionModel class to check/change/other selection(s)

Example:

QItemSelectionModel *select = table->selectionModel();

select->hasSelection() //check if has selection
select->selectedRows() // return selected row(s)
select->selectedColumns() // return selected column(s)
...
Angie Quijano
  • 4,167
  • 3
  • 25
  • 30
Luca
  • 845
  • 8
  • 8
  • 2
    For reference: the method was [inherited from `QAbstractItemView`](http://doc.qt.io/qt-5/qabstractitemview.html#selectionModel). – user202729 Jul 01 '18 at 06:29
20

Check selectedRows method of the QItemSelectionModel Class .

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

// Multiple rows can be selected
for(int i=0; i< selection.count(); i++)
{
    QModelIndex index = selection.at(i);
    qDebug() << index.row();
}
Alexander
  • 12,424
  • 5
  • 59
  • 76
9

try:

QModelIndexList indexList = yourTableView->selectionModel()->selectedIndexes();
int row;
foreach (QModelIndex index, indexList) {
    row = index.row();
    ....
}
louis.luo
  • 2,921
  • 4
  • 28
  • 46
  • 3
    I wonder if you parse a column, will you drop the same row twice (or more likely some other row). – Mikhail Jan 06 '14 at 05:06
1

Since you use

setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::SingleSelection);

so only one row can be selected each time, then you can try this:

auto rowList = yourTableView->selectionModel()->selectedRows();
if(rowList.count() > 0)
    int rowNumber = rowList.constFirst().row();
else
    // no row is selected
Brett Li
  • 25
  • 6