how to get selected rows in QTableView
Asked Answered
F

4

63

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!

Framing answered 8/5, 2011 at 12:45 Comment(0)
C
79

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)
...
Cleora answered 27/7, 2011 at 7:10 Comment(1)
For reference: the method was inherited from QAbstractItemView.Boodle
A
22

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();
}
Airdry answered 22/1, 2015 at 9:47 Comment(1)
Is it possible to do this with the model name instad of the table name?Odontalgia
C
9

try:

QModelIndexList indexList = yourTableView->selectionModel()->selectedIndexes();
int row;
foreach (QModelIndex index, indexList) {
    row = index.row();
    ....
}
Corry answered 31/12, 2011 at 18:0 Comment(1)
I wonder if you parse a column, will you drop the same row twice (or more likely some other row).Enriqueenriqueta
A
1

Since you use

yourTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
yourTableView->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
Adhamh answered 27/7, 2022 at 14:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.