如何在QTableView中获取选定的行

问题描述 投票:0回答:4

在观看了许多有关获取选定行数的线程后,我真的很困惑。

如何使用

QTableView
获取
QStandardItemModel
中的 ROW 数字我使用下面的选择模型和行为作为

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

如果您有自己的选择方式,您能否解释一下它是如何工作的。 感谢您的帮助!

qt row qtableview
4个回答
78
投票

方法

selectionModel()
返回一个
QItemSelectionModel

您可以使用

QItemSelectionModel
类来检查/更改/其他选择

示例:

QItemSelectionModel *select = table->selectionModel();

select->hasSelection() //check if has selection
select->selectedRows() // return selected row(s)
select->selectedColumns() // return selected column(s)
...

22
投票

检查

selectedRows
类的
QItemSelectionModel
方法。

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

9
投票

尝试:

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

1
投票

自从你使用

yourTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
yourTableView->setSelectionMode(QAbstractItemView::SingleSelection);

所以每次只能选择一行,那么你可以试试这个:

auto rowList = yourTableView->selectionModel()->selectedRows();
if(rowList.count() > 0)
    int rowNumber = rowList.constFirst().row();
else
    // no row is selected
© www.soinside.com 2019 - 2024. All rights reserved.