[Qt-interest] QSqlTableModel and autoincrement fields

Harry Sfougaris hsfougaris at gmail.com
Sun Oct 24 21:43:24 CEST 2010


Hi,
How am I supposed to retrieve the value of an autoincrement field of the last inserted record in QSqlTableModel?
I am trying to use it with a postgresql table, but I can't really make sense of it...
I've created a table using OIDS=true as stated in the documentation:

CREATE TABLE helpers.currencies
(
  id serial NOT NULL,
  descr character varying(100) NOT NULL,
  CONSTRAINT currencies_pkey PRIMARY KEY (id),
  CONSTRAINT currency_uq_descr UNIQUE (descr)
)
WITH (
  OIDS=TRUE
);


In my code, I use

    QSqlTableModel *dataRecord = new QSqlTableModel();
    dataRecord->setTable("helpers.currencies");
    dataRecord->insertRow(0);
    QDataWidgetMapper *dwMapper = new QDataWidgetMapper;
    dwMapper->setModel(dataRecord);
    dwMapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
    dwMapper->addMapping(ui->curr_descr, dataRecord->fieldIndex("descr"));
    dwMapper.setCurrentIndex(0);
    ui.curr_descr.setText("Test");
    if (!dwMapper->submit()) {
        QMessageBox::critical(0, QObject::tr("Error saving record"), dataRecord->lastError().text());
        return false;
    } else {
	qDebug() << "Last ID = " << dataRecord->query().lastInsertId()
}

This successfully saves the record in the table/database, but the call to lastInsertId() returns an empty QVariant.
Calling dataRecord->database().driver()->hasFeature(QSqlDriver::LastInsertId) returns true, so I don't know what else to check.
I tried setting 
- setGenerated to true and false for the field "id" in the beforeInsert signal, which doesn't seem to affect anything
- setAutoValue to true for the field "id" in the beforeInsert signal, but it doesn't seem to work (calling isAutoValue returns false).

Thanks,
Harry

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20101024/905a9928/attachment.html 


More information about the Qt-interest-old mailing list