In my Qt 6.6.0 application I set up a QSqlTableModel
and a QTableView
with sorting enabled:
QSqlTableModel *model;
model = new QSqlTableModel(this, db);
model->setTable("table");
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
model->sort(0, Qt::AscendingOrder);
model->select();
ui->tableDb->setModel(model); // QTableView
I add a record in this way:
QSqlRecord record = model->record();
record.setValue("col1", value1);
// ...
for (int i = 0; i < record.count(); i++) record.setGenerated(i, true);
bool ret = true;
ret &= _model->insertRecord(-1, record);
ret &= _model->submitAll();
if (!ret) return false;
ui->tableDb->selectRow(???);
I want to select the row of the last inserted record.
Since I have sorting enabled, I don't know where the record is placed in the QTableView
.
How to retrieve its "visual" position from the model index?
Looking at the QTableView
docs I found nothing relevant.
There is a scrollTo()
function but it just ensures the record is visible, not selected.
I'm looking for something like a QTableView::selectRow(const QModelIndex &index)
function...
I had to use a QSortFilterProxyModel
:
QSqlTableModel *model;
QSortFilterProxyModel *proxyModel;
model = new QSqlTableModel(this, db);
model->setTable("table");
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
model->select();
proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model);
proxyModel->sort(0);
ui->tableDb->setModel(proxyModel);
// ...
QModelIndex index = proxyModel->mapFromSource(model->index(model->rowCount() - 1, 0));
ui->tableDb->selectionModel()->setCurrentIndex(index, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
In this way I can retrieve the correct QModelIndex
of the QTableView
from the index of the QSqlTableModel
.