qtqtsqlqsqltablemodelqsqldatabase

Error on Submit after Inserting a Row in QSqlTableModel - No Fields to update


I have a SQLite database table with the following schema:

TABLE IenState (
   Id      primary key,
   NetId   integer,
   NodeId  integer,
   DevType text
   Qos     integer      
)

Using a DB Browser utility I inserted a record in the table.
I wrote a Qt program to interact with the database. From the program I can read the record that exits in the table. However when I try to insert a new record I get following error:

No Fields to update.

The error occurs when I submit changes to the table. The following code snippet shows how I am performing the insert operation.

QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("file.db");
if (!db.isOpen()) {        
   qFatal("Failed to open database");          
}

QSqlTableModel model(nullptr, db);
model.setEditStrategy(QSqlTableModel::OnManualSubmit);
model.setTable("IenState");
model.select();

int idRow = model.rowCount();
if (!model.insertRows(idRow, 1)) {
    qFatal("Row insertion FAILED");
}
QSqlRecord record = model.record(idRow);

record.setValue("Id", 3);
record.setValue("NetId", 0);
record.setValue("NodeId", 1);
record.setValue("DevType", "sm");
record.setValue("Qos", 95);

if (!model.setRecord(idRow, record)) {
    qFatal("Setting record FAILED");
}

if (!model.submitAll()) {
    qFatal("Submitting Failed. Error: %s, %d",
        qPrintable(model.lastError().text()),
        model.lastError().type());
}

The code fails at model.submitAll() operation with Submitting Failed. Error: No Fields to update, 2. I verified, QSqlRecord record has field names according to the database schema, and record.setValue operations works fine. I am unable to find out cause of the failure.


Solution

  • You use idRow which is set to row count. As it is a zero based index, you cannot use idRow, but you have to use idRow - 1.

    Also, if you want to add a new record to the end, use -1 as index to insertRecord().

    You can ask a clean record by model.record(), without an index. This record you can use to fill and insert.