[Qt-interest] Models don't work when created BEFORE adding the first database

Sven Grunewaldt strayer at olle-orks.org
Tue Feb 10 19:12:58 CET 2009


I have an application that uses two Model/Views to display a table of a 
SQLite database.

After creating the UI and initializing the models the User can click on 
an action which opens the SQLite database. Sadly the Models only work 
when they are created AFTER I opened a database, if I don't add a 
database first they don't display anything. How should I design the 
application with this in mind?

The Models are initialized in the constructor:
     schuleModel = new QSqlTableModel(this);
     schuleModel->setTable("entry");
     schuleModel->setFilter("1 = 0"); // Gets changed by signals
     schuleModel->setHeaderData(1, Qt::Horizontal, tr("Fach"));
     schuleModel->setHeaderData(2, Qt::Horizontal, tr("Thema"));
     schuleModel->setEditStrategy(QSqlTableModel::OnFieldChange);
     schuleModel->select();

     // Betriebtabelle
     betriebModel = new QSqlTableModel(this);
     betriebModel->setTable("entry");
     betriebModel->setFilter("1 = 0"); // Gets changed by signals
     betriebModel->setEditStrategy(QSqlTableModel::OnFieldChange);
     betriebModel->select();

This action that opens the database:
     QString fileName = QFileDialog::getOpenFileName(this,
         tr("Datenbank öffnen"),
         ".",
         tr("Datenbank (*.sqlite)"));
     dataHandler.openDatabase(fileName);

The class that manages the database:
bool DataHandler::openDatabase(QString file)
{
     // Ggfs. alte DB schließen
     if (db.isOpen())
         db.close();

     db = QSqlDatabase::addDatabase("QSQLITE");
     db.setDatabaseName(file);

     if (!db.open())
     {
         QMessageBox::critical(0, QObject::tr("Datenbankfehler!"),
             db.lastError().text());
         return false;
     }

     return true;
}



More information about the Qt-interest-old mailing list