看了很多关于获取选定行号的线程后,我真的很困惑。
如何在使用QStandardItemModel
时,在QTableView
中获取行号。我使用下面的选择模型和行为:
setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::SingleSelection);
如果您有自己的选择方式,能否解释一下它是如何工作的。感谢帮助!
看了很多关于获取选定行号的线程后,我真的很困惑。
如何在使用QStandardItemModel
时,在QTableView
中获取行号。我使用下面的选择模型和行为:
setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::SingleSelection);
如果您有自己的选择方式,能否解释一下它是如何工作的。感谢帮助!
方法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)
...
请查看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();
}
尝试:
QModelIndexList indexList = yourTableView->selectionModel()->selectedIndexes();
int row;
foreach (QModelIndex index, indexList) {
row = index.row();
....
}
由于您使用的
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
QAbstractItemView
继承而来的(http://doc.qt.io/qt-5/qabstractitemview.html#selectionModel)。 - user202729