PDA

View Full Version : QSqlTableModel and insertRecord()



Hostel
5th September 2011, 02:45
I'm trying use a Model / View framework. I know how to make model and how to display data with QTableView and how to use QDataWidgetMapper. But I have problem with QDataWidgetMapper when I want to insert new record. Actualy I use something like this:



QSqlRecord record = model->record();

// append new record
model->insertRecord( -1, record );

mapper = new QDataWidgetMapper();
mapper->setModel( _model );
mapper->addMapping( )
mapper->addMapping( )
mapper->addMapping( )

// HERE IS MY QUESTION
mapper->setCurrentIndex( model->rowCount() - 1 );


I use


mapper->setCurrentIndex( model->rowCount() - 1 );

but rowCount doesn't have a true row count. How can I insert a record and set up an edit on this empty new record in safe way?

ChrisW67
5th September 2011, 04:41
Are model, the one you insert to, and _model, the one your mapper looks at, the same object? Is that just a typo?

Hostel
5th September 2011, 12:11
Are model, the one you insert to, and _model, the one your mapper looks at, the same object? Is that just a typo?
It is a typo.

ChrisW67
6th September 2011, 00:25
What is the editStrategy() on the model?

This code:


#include <QtCore>
#include <QtSql>
#include <QDebug>


int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);


QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
db.open();
QSqlQuery query;
query.exec("CREATE TABLE test (a INTEGER, b VARCHAR(10))");
query.exec("INSERT INTO test VALUES (1, 'One')");
query.exec("INSERT INTO test VALUES (2, 'Two')");
query.exec("INSERT INTO test VALUES (3, 'Three')");


QSqlTableModel model;
model.setTable("test");
model.select();

// model.setEditStrategy(QSqlTableModel::OnRowChange) ;
model.setEditStrategy(QSqlTableModel::OnManualSubm it);

qDebug() << "Starting with" << model.rowCount();
for (int i = 0; i < 20; ++i) {
QSqlRecord record = model.record();
qDebug() << i << model.rowCount();
model.insertRecord(-1, record);
}
return app.exec();
}

Works as expected with one value and not the other.

Hostel
6th September 2011, 00:42
Thanks for your reply. I think that I now know how to work with Model / View Framework.