How to provide an empty row in QTableView
-
In my Qt 6.8.0 application I display a SQlite table:
// ...open db and create tables QSqlTableModel *_model; QSqlDatabase db = QSqlDatabase::database("mydb"); _model = new QSqlTableModel(this, db); _model->setTable("mytable"); _model->setEditStrategy(QSqlTableModel::OnRowChange); _model->select();
I want to provide an empty row at the end of the table to let the user to add a new record without using a
QPushButton
.
Something like:_model->insertRows(_model->rowCount(), 1);
that leads to:
Of course this does not work as expected since the record is already in edit mode. Until I insert a valid data I cannot edit other rows.
Please note that my tables have not null keys, so I can't just add and save an empty record.
-
Hi,
One possible way is to use a proxy model that returns the number of rows + 1 and when editing that row, calls whatever is necessary to create the row before adding data to it.
-
@SGaist actually, I already have a proxy model:
QSqlTableModel *_model; QSortFilterProxyModel *_proxyModel; QSqlDatabase db = QSqlDatabase::database("mydb"); _model = new QSqlTableModel(this, db); _model->setTable("mytable"); _model->setEditStrategy(QSqlTableModel::OnRowChange); _model->select(); _proxyModel = new QSortFilterProxyModel(this); _proxyModel->setSourceModel(_model); _proxyModel->sort(1); ui->table->setModel(_proxyModel);
is there a way to use this proxy to do what you suggested or I have to create a new subclass of
QSortFilterProxyModel
which in turn inheritsQAbstractProxyModel
? -
@Mark81
You could subclass, so_proxyModel = new SubClassedSortFilterProxyModel(this);
, and implement the extra row there. But I think I'd leave that as-is because it's useful, and interpose a newQIdentityModel
-subclass on top of it to just provide the dummy row for editing when required. -
@JonB yeah, it works. Basically I did the following:
class AddIdentityProxyModel : public QIdentityProxyModel { public: AddIdentityProxyModel(QObject *parent = 0): QIdentityProxyModel(parent) { } int rowCount(const QModelIndex &parent = QModelIndex()) const { return sourceModel()->rowCount() + 1; } };
then
QSqlTableModel *_model; QSortFilterProxyModel *_proxyModel; AddIdentityProxyModel *_addProxy; QSqlDatabase db = QSqlDatabase::database("mydb"); _model = new QSqlTableModel(this, db); _model->setTable("mytable"); _model->setEditStrategy(QSqlTableModel::OnRowChange); _model->select(); _proxyModel = new QSortFilterProxyModel(this); _proxyModel->setSourceModel(_model); _proxyModel->sort(1); _addProxy = new AddIdentityProxyModel(this); _addProxy->setSourceModel(_proxyModel); ui->table->setModel(_addProxy);
it needs some tweaks in order to be fully functional, but I think it could work!
-