I'm using QtSql (sqlite database in memory) and I need to remove the first column from my tables. Unfortunately, when I do this and I attempt to change a value using setData() I get a "QSqlQuery::value: not positioned on a valid record" error yet I'm able to retreive the current valus using a call to data() using the exact same QModelIndex. Has anyobody ever seen this problem or have a work around? Below is an example which show the problem. To remove the first column, you just need to run the compiled binary with at least one argument:

Qt Code:
  1. #include <QtGui>
  2. #include <QtSql>
  3. #include <QWidget>
  4. #include <QDebug>
  5. #include <iostream>
  6.  
  7.  
  8.  
  9.  
  10. int main(int argc, char *args[])
  11. {
  12. QApplication app(argc, args);
  13.  
  14. // Create an im memory database
  15. QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
  16. db.setDatabaseName( ":memory:" );
  17. if ( !db.open() )
  18. {
  19. qCritical( "ERROR in opening the internal database" );
  20. }
  21.  
  22. // Create a table in the database
  23. QSqlQuery query = db.exec(QString("create table test (id INTEGER PRIMARY KEY AUTOINCREMENT)"));
  24. // Add a column in the table using a query
  25. query.exec("ALTER TABLE test ADD col2 VARCHAR(50);");
  26. query.exec("ALTER TABLE test ADD col3 VARCHAR(50);");
  27. // Add a row to the column
  28. query.exec("INSERT INTO test ('col2','col3') VALUES ('something','last');");
  29.  
  30.  
  31.  
  32. bool removeFirstColumn = argc > 1;
  33.  
  34. // Create a table model for the table view
  35. model->setTable("test");
  36. model->setEditStrategy(QSqlTableModel::OnFieldChange);
  37. if (removeFirstColumn) {
  38. model->removeColumns(0,1);
  39. }
  40. model->select();
  41. // Cteate a table view and display it
  42. QTableView table;
  43. table.setModel(model);
  44. table.show();
  45.  
  46.  
  47.  
  48. int row = 0;
  49. int col ;
  50. if (removeFirstColumn) {
  51. col = 1 ;
  52. } else {
  53. col = 2;
  54. }
  55. QModelIndex index = model->index(row, col);
  56. //NOTE: current value should be "last", this works
  57. qDebug() << "value before change at row=" << row << "col=" << col << model->data( index ).toString();
  58.  
  59.  
  60. //Attempt to change the value
  61. QVariant newValue = "new value";
  62. model->setData( index, newValue);
  63. qDebug() << "value after change at row=" << row << "col=" << col << model->data( index ).toString();
  64.  
  65. return app.exec();
  66. }
To copy to clipboard, switch view to plain text mode 

Below is my output:
C:\Qt\examples\sql>sql remove
value before change at row= 0 col= 1 "last"
QSqlQuery::value: not positioned on a valid record
value after change at row= 0 col= 1 "last"