⚠️ Forum Maintenance: Feb 6th, 8am - 14pm (UTC+2)

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->setOrderIdFilter( dto.orderId);

    _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());

  • Check whether setData returns true (i.e. the data were successfully set).

  • You have used
    Is there a corresponding submitAll() in your code?

  • Dialingo, there is, if I understand thing correctly, the phone number should show up without calling submitAll().

    I will check the return code what I get to my PC (on an iPad right now, cannot wait for it to be a MeeGo)

  • 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!


Log in to reply