How to insert new record in a QSqlRelationalTableModel
-
I have a form which opens a child form (addArticle).
When the child opens, I want to:- insert a new record
- map controls (a LineEdit & a Combo Box) to the model
I 've done it as shown below, but the data I enter in the controls does not get saved to the database. (model 's Edit Strategy is OnFieldChange)
What am I doing wrong?This is the child 's constructor:
addArticle::addArticle(QSqlRelationalTableModel *model, int *Idx, QDataWidgetMapper *mapper, QWidget *parent) : QDialog(parent), ui(new Ui::addArticle){ ui->setupUi(this); this->model = model; //add new Record ; QSqlRecord newRecord = model->record(); // if successfull insertion if (model->insertRecord(-1, newRecord)) { mapper->toLast(); qDebug() << "New record inserted"; }else{ // if failed qDebug() << "New record NOT inserted!!!"; } // bound field for combo is field 'position' ui->positionEdit->setModel(model->relationModel(*Idx)); // display field for combo is field 'name' ui->positionEdit->setModelColumn(model->relationModel(*Idx)->fieldIndex("name")); // map controls to data mapper->addMapping(ui->nameEdit, model->fieldIndex("name")); mapper->addMapping(ui->positionEdit, *Idx); mapper->toLast(); }
-
Hi,
Is your mapper submit policy AutoSubmit ?
-
What happens if you manually call submit on the mapper ?
-
The same: a new record is created but only the autoincremented field is filled, the others are empty, null.
I tried mapper->submit() and model->submitAll().Maybe it's because mapping is happening in the constructor of the form? And the controls on the form have not yet been fully created?
-
Are you sur the mapper is valid ?
Why is it not part of your dialog rather than passed around ? -
Check the current index.
-
Your record is empty - so what's your db structure. Does it allow NULL values, has it a PK?
-
The table does have a primary key.
The record gets inserted in the database, so I guess it allows NULL values. -
This post is deleted!
-
I want to use it in the child for inserting a new record. mx player for pc mxplayer
-
The logic should be the other way around.
Use the dialog to get the data from your application user. Then create the record based on the data you extract from the dialog.
This will also allow you to properly handle cancellation of the dialog. Otherwise you may end up with empty rows in the database that you will need to remove because you added it too early in your business logic.