如何在QTableView中获取选定行

61

看了很多关于获取选定行号的线程后,我真的很困惑。

如何在使用QStandardItemModel时,在QTableView中获取行号。我使用下面的选择模型和行为:

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

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

4个回答

77

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

2
参考:该方法是从QAbstractItemView继承而来的(http://doc.qt.io/qt-5/qabstractitemview.html#selectionModel)。 - user202729

22

请查看QItemSelectionModel类的selectedRows方法。

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

能否使用模型名称而不是表名来完成这个操作? - Thomas Williams

9

尝试:

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

3
如果你解析一列,是否会删除相同的行两次(或更可能是其他行)。 - Mikhail

1

由于您使用的

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

如果您只想每次选择一行,可以尝试以下方法:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接