PDA

View Full Version : updating QTableView with new qsl columns



sylvainb
28th January 2009, 17:47
I'm writing an application using QtSql and the columns of my tables can't be determined when the table is created. When I add columns to the database, I'm not able to add the column to the table view and I may also get extra empty rows added to my table view. I wrote a small example which demonstrates the problem. DOes anyone have any suggestions?


class MyTable : public QTableView
{
Q_OBJECT

public:
MyTable() : QTableView() {
}

};

int main(int argv, char *args[])
{
QApplication app(argv, args);

// Create an im memory database
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
db.setDatabaseName( ":memory:" );
if ( !db.open() )
{
qCritical( "ERROR in opening the internal database" );
}

// Create a table in the database
QSqlQuery query = db.exec(QString("create table test (id INTEGER PRIMARY KEY AUTOINCREMENT)"));

// Create a tavle model for the table view
QSqlTableModel *model= new QSqlTableModel;
model->setTable("test");
model->setEditStrategy(QSqlTableModel::OnFieldChange);
model->select();

// Cteate a table view and display it
QTableView table;
table.setModel(model);
table.show();


// Add a column in the table using a query
query.exec("ALTER TABLE test ADD col2 VARCHAR(50);");
if (query.isActive())
qDebug() << "query active after column insertion" ;
// Add a row to the column
query.exec("INSERT INTO test ('col2') VALUES ('something');");
if (query.isActive())
qDebug() << "query active after row insertion" ;


// reload the data? Not sure if this is needed or valid
model->select();

return app.exec();
}

Below is what my table view looks like with the empty row and missing column:
http://i40.tinypic.com/vo90ts.jpg

sylvainb
28th January 2009, 20:43
It turns out the code above was missing a second setTable() to re-fetch the sql table field information.


model->setTable("test");
model->select();


return app.exec();

montylee
28th January 2009, 21:51
i think once your database tables are updated and you want to update the QTableView you just need to call reset() API of the model. It'll automatically update QTableView with the latest stuff from model.