QSqlRelationalTableModel update table model

From QT Wikipedia

Jump to: navigation, search

Then you are working with SqlRelationalTableModel and using foreign keys you may get SQL error trying to update record. It's because in generated SQL "WHERE" statement contains virtual column, witch actually does not exist. I spend almost 6h trying make update work. In Sql documentation there were actually written notice

The table must have a primary key declared

Then i tried directly use "setPrimaryKey",it did not worked, because this function is declared as protected in SqlRelationalTableModel, so to make it work properly i had to make my own relation table model based on SqlRelationalTableModel.

xpsqlrelationtablemodel.h

 
#ifndef XPSQLRELATIONTABLEMODEL_H
#define XPSQLRELATIONTABLEMODEL_H
 
#include <QtSql>
 
class XPSqlRelationalTableModel : public QSqlRelationalTableModel
{
    Q_OBJECT
 
public:
    explicit XPSqlRelationalTableModel(QObject *parent = 0,
                                      QSqlDatabase db = QSqlDatabase());
    virtual ~XPSqlRelationalTableModel();  
    void setPrimaryKey(const QString &);  
 
};
#endif
 

xpsqlrelationtablemodel.cpp

 
#include "xpsqlrelationtablemodel.h"
 
#include <QSqlIndex>
 
XPSqlRelationalTableModel::XPSqlRelationalTableModel(QObject *parent, QSqlDatabase db)  : QSqlRelationalTableModel(parent, db)
{
 
}
 
/*!
    Destroys the object and frees any allocated resources.
*/
XPSqlRelationalTableModel::~XPSqlRelationalTableModel()
{
 
}
 
void XPSqlRelationalTableModel::setPrimaryKey(const QString &keyColumn)
{
   QSqlIndex index = this->primaryKey();
   QSqlField f1(keyColumn, QVariant::LongLong);
   index.append(f1);
   QSqlRelationalTableModel::setPrimaryKey(index);
}
 

Usage example

 
#include "xpsqlrelationtablemodel.h"
...
model = new XPSqlRelationalTableModel(this);
model->setTable("dummy_table");
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
 
model->setPrimaryKey("id"); //Column name on witch update WHERE statement should be generated
 

So now SQL update query is generated properly example:

 
... WHERE "id" = 20
 

One more thing. In Qt version 4.3.1 after update you canned do second update because DataWidgetMapper retur's false with no proper exaplanation why. Workaground

 
int index = mapper->currentIndex();
mapper->submit();
model->submitAll();     
mapper->setCurrentIndex(index);
 

Personal tools
Toolbox