PDA

View Full Version : Getting the Primary Key value for a new record in mapper



pcheng
19th December 2012, 08:57
I have a qdatawidgetmapper which I use to browse through data from a specific table in MySQL.


// Setup the model to use in the mapper
model = new QSqlRelationalTableModel(this);
model->setTable("Customers");
model->select();

// Setup the mapper for the product widgets
mapper = new QDataWidgetMapper(this);
mapper->setModel(model);
mapper->addMapping(ui->cNumLineEdit, 0);
mapper->addMapping(ui->nameLineEdit, 1);
mapper->addMapping(ui->frequencyComboBox, 2, "currentIndex");
mapper->addMapping(ui->priorityComboBox, 3, "currentIndex");
mapper->addMapping(ui->typeComboBox, 4, "currentIndex");
mapper->addMapping(ui->address1LineEdit, 5);
mapper->addMapping(ui->address2LineEdit,6);
mapper->addMapping(ui->cityLineEdit,7);
mapper->addMapping(ui->postalCodeLineEdit,8);
mapper->addMapping(ui->telephoneLineEdit,9);

I try to create a new record and it creates normally but the primary key is an autoincrement number provided from MySQL. I would like to refresh the record to include the number in the form. I believe that not having the value produces errors when trying to save data or add other data which are related to the new record.


void Customers::on_newPushButton_clicked()
{
// Create a new item and clear all widgets
QSqlRecord sqlRecord1;
model->insertRecord(-1,sqlRecord1);

ui->cNumLineEdit->clear();
ui->nameLineEdit->clear();
ui->address1LineEdit->clear();
ui->address2LineEdit->clear();
ui->cityLineEdit->clear();
ui->postalCodeLineEdit->clear();
ui->telephoneLineEdit->clear();
mapper->toLast();
}


Can anyone tell me if I am doing it correctly or if I need to insert the record and retrieve it in a different way?

Thanks,

Pericles

ChrisW67
19th December 2012, 22:24
Until the model actually tries to put the new record into the database there is no MySQL allocated number to access. When it does that is dependent on the update strategy. The submit() or submitAll() calls can force writing to the database, but this will fail if other relevant constraints are not met.

You may be able to mark the auto-numbered id column, see QSqlRecord::setGenerated(), to stop the Qt code trying to insert NULL into that column (assuming that's an error you are seeing).

IMHO this sort of surrogate primary key should never have a meaning to the user and thus never need to be displayed except, perhaps, for debugging purposes.