Adding a new row with QSqlTableModel and QDataWidgetMapper
-
I have an order form that, there are two tables used: Order and OrderItem. The Order contains all the standard stuff like username, address, etc. I do have a OrderModel that derives from QSqlTableModel and on the form there is a control for each relevant column. The one and only field I have ahead of time is the phone number. So here is my code to create a new row in the model, set the phone number and then wire up the mapper, but the phone number is never set. What am I missing?
@_orderModel = new OrderModel(this, _db);
_orderModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
if(dto.orderId)
{
_orderModel->setOrderIdFilter( dto.orderId);
_orderModel->select();
}
else
{
_orderModel->insertRow(0);
}_orderModel->setData(_orderModel->index(0, _orderModel->phoneNo()), dto.phonenumber);
_orderMapper = new QDataWidgetMapper(this);
_orderMapper->setModel( _orderModel);_orderMapper->addMapping(ui.firstNameEdit, _orderModel->fnameNo());
_orderMapper->addMapping(ui.lastNameEdit, _orderModel->lnameNo());
_orderMapper->addMapping(ui.address1Edit, _orderModel->address1No());
_orderMapper->addMapping(ui.address2Edit, _orderModel->address2No());
_orderMapper->addMapping(ui.cityEdit, _orderModel->cityNo());
_orderMapper->addMapping(ui.stateEdit, _orderModel->stateNo());
_orderMapper->addMapping(ui.zipEdit, _orderModel->zipNo());
_orderMapper->addMapping(ui.emailEdit, _orderModel->emailNo());
_orderMapper->addMapping(ui.phoneEdit, _orderModel->phoneNo());
_orderMapper->toFirst();@ -
opps, I never called QSqlTableModel::setTable(). Added an Q_ASSERT to the macro that gets the column id's so should have that problem again. Don't know why so many folks hate macro's, they sure speed up development when used correctly:)
Ok, next issue. How do I get the primary key from this inserted row?
In the beforeInsert() slot, the PK column is being set to not be generates so the SQLite's AUTOINCREMENT can do it thing:
record.setGenerated(_orderModel->orderIdNo(), false);
Here is the little catch, I know for an absolute FACT, in the very near feature the DB will be converted over to Firebird, which does NOT have a AUTOINCREMENT concept like most DB's.
So ideally if there is a way to get the PK that will work today for SQLite and tomorrow for Firebird, that would be ideal!
Sam