2

I am trying to update a record and i have this:

tableModel->select();
QModelIndex index = ui.tableView->currentIndex();
QString sqlQuery = QString("UPDATE %1 SET firstname=:firstname, lastname=:lastname,  country=:country, city=:city WHERE id=:id)").arg(tableName);
query.prepare(sqlQuery);
QSqlRecord recordz = tableModel->record(index.row());

query.bindValue(":firstname", ui.fEdit->text());
query.bindValue(":lastname",  ui.lnEdit->text());
query.bindValue(":country", ui.cEdit->text());
query.bindValue(":city",  ui.cityEdit->text());
query.bindValue(":id", recordz.value("id").toInt());
query.exec();
tableModel->submitAll();

The application compiles without errors but it won't save any edits.

RAM
  • 2,257
  • 2
  • 19
  • 41
Gandalf
  • 1
  • 29
  • 94
  • 165
  • 1
    Use [`QModelIndex::data()`](http://doc.qt.nokia.com/4.7/qmodelindex.html#data) instead of the `QModelIndex` object directly. – manatwork Sep 12 '11 at 07:16

1 Answers1

1
    query.bindValue(":id", ui.tableView->currentIndex());

There's your offending line of code. You can use the data functions to try return the actual index or value, but remember your tableView index != your SQL database index. You ever drop a row your index on database will be different to your index in Qt, so you'll need to include the actual DB ID into your initial SQL queries and keep it stored alongside the other values, and then return it when you run your update query.

Nicholas Smith
  • 11,642
  • 6
  • 37
  • 55
  • I now have query.bindValue(":id", tableModel->data(index, Qt::DisplayRole)); but still cannot be able to update. – Gandalf Sep 12 '11 at 09:48
  • Try query.bindValue(":id", tableModel->record(index.row).value("id")). That does mean you need to include the items ID into your tableView, but you can include it and then mark it as a hidden field. It's a bit of a longer approach (and there's probably a better one), but it's reliable. – Nicholas Smith Sep 12 '11 at 10:00
  • I get the error no matching function for call to 'QSqlTableModel::record(unresolved overloaded function type>)' when using query.bindValue(":id", tableModel->record(index.row).value("id"));.I have the ID column displayed in the QTableView. – Gandalf Sep 12 '11 at 10:33