1

I have a simple QSqlTableModel:

class UsersModel : public QSqlTableModel
{
    Q_OBJECT
public:
    UsersModel();
    ~UsersModel();

    bool newUser(const QString &name, const QString &surname, const QString &birthday);
};

UsersModel::UsersModel()
{
    setTable("users");
    select();
}

When I'm inserting a new record into the model, it is inserted into the database, but immediate retrieving of this record from the model doesn't work:

bool UsersModel::newUser(const QString &name, const QString &surname, const QString &birthday)
{
    QSqlRecord rec = record();
    rec.setGenerated("id", true);
    rec.setValue("name", QVariant(name));
    rec.setValue("surname", QVariant(surname));
    rec.setValue("birthday", QVariant(birthday));

    bool res = insertRecord(-1, rec);
    if (res) {
        qDebug() << "last inserted id:" << query().lastInsertId();
        qDebug() << "name: " << record(rowCount() - 1).value("name");
    }

    return res;
}

Result of newUser method call:

last inserted id: QVariant(qlonglong, 31)
name: QVariant(Invalid)

If I look into the database, record is inserted, but if I try to get it from the model, invalid QVariant is returned.
What I'm doing wrong? Shouldn't the model return data for the newly inserted record?

Pavel K.
  • 11
  • 3
  • What is the edit strategy of your model? Try to set it to `QSqlTableModel::OnFieldChange` and check the result. – Nejat Mar 19 '15 at 08:02
  • Are you assuming that `query().lastInsertId()` is the same is `rowCount() - 1`? It's not always so. – Pavel Strakhov Mar 19 '15 at 21:56
  • @PavelStrakhov According to the docs: `QSqlRecord QSqlQueryModel::record ( int row ) const` Returns the record containing information about the fields of the current query. If row is the index of a valid row, the record will be populated with values from that row. -- I assume that the inserted record is the last one in the model, therefore `rowCount() - 1` should be the index of the last row. -- Could be that it's wrong assumption, but again according to the doc `insertRecord(-1, rec)` should append the row to in the model. – Pavel K. Mar 19 '15 at 23:11
  • New entry may appear in the middle of the table depending on your model's sort settings. – Pavel Strakhov Mar 20 '15 at 11:01
  • @PavelStrakhov Hmm..ok, but still `record(rowCount() - 1).value("name")` should return last record from the model, regardless of the id of that record. It is model's responsibility to return correct number of rows in `rowCount()` method. – Pavel K. Mar 20 '15 at 14:31

0 Answers0