PDA

View Full Version : Understanding QSqlTableModel/QDataWidgetMapper when editing one record...



scarleton
4th October 2010, 00:18
I have the PK of the row in a table which needs to be edited. I want to display a form that will allow the user to edit the one record, when the user presses the <Save> button, the information is updated in the database.

There shouldn't be any change on the DB if no data was actually changed. This can be achieved by either only enabling the <Save> button when a change to the data has happened or by simply doing nothing when the <Save> button is pressed, which ever requires the least amount of code.

There is on catch, though. There is an audit field that contains the last modified user id. Aka the id of the user that is making the change, this needs to be set correctly for the update.

Is it possible to use the QSqlTableModel and QDataWidgetMapper to do this and minimize the amount of code I have to write?

I have wired up the construction of the form using both the model and the mapper and data appears correctly! The problem is on the save, nothing is ever saved to the database.

The last three lines of the constructor are:



_model->setFilter(QString("PARISHNER_ID = %1").arg(parishionerId));
_model->select();
_mapper->toFirst();


Currently I am trying the approach of the Save button is always enabled and I look to see if the model has changed to do the submit:



bool isDirty = false;
for(int idx = 0; isDirty == false && idx < _model->columnCount(); idx++)
isDirty += _model->isDirty(_model->index(0, idx));

if(isDirty)
{
QModelIndex modelIndex = _model->index(0, _model->fieldIndex("UPDATEDBY"));
_model->setData(modelIndex, _parishionerId);
_model->submit();
}

The problem is that isDirty ALWAYS gets set immediately and the _model->submit() doesn't actually do anything.

Any thoughts?

Sam

scarleton
4th October 2010, 00:46
Ok, looks like I figured it out how to get it to submit, it was a bug on my part:

I first added a qDebug() statement after the submit and it gave me nothing:



_model->submit();
qDebug() << "lasterror: " << _model->lastError().text();


After stepping into the sumbit code, I saw there was an if condition in the QSqlTableModel::submit() function checking the strategy of the model, which was failing so the submit did nothing. When I changed the code to call submitAll() it worked. Then I changed the editStrategy to OnRowChange and it works fine.

Ok, as far as the dirty flag goes, I found a way to not have to worry about it, fore my concern was setting UPDATEDBY field. What I did was simply connected to the model's beforeUpdate signal and set the UPDATEDBY field there, once the model has determined there is something to change.

Sam