how to get selected rows in QTableView

QtRowQtableview

Qt Problem Overview


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!

Qt Solutions


Solution 1 - Qt

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)
...

Solution 2 - Qt

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();
}

Solution 3 - Qt

try:

QModelIndexList indexList = yourTableView->selectionModel()->selectedIndexes();
int row;
foreach (QModelIndex index, indexList) {
    row = index.row();
    ....
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionshett73View Question on Stackoverflow
Solution 1 - QtLucaView Answer on Stackoverflow
Solution 2 - QtAlexanderView Answer on Stackoverflow
Solution 3 - Qtlouis.luoView Answer on Stackoverflow