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?
{
Q_OBJECT
public:
}
};
int main(int argv, char *args[])
{
// Create an im memory database
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
model->setTable("test");
model->select();
// Cteate a table view and display it
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();
}
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();
}
To copy to clipboard, switch view to plain text mode
Below is what my table view looks like with the empty row and missing column:
Bookmarks