QTableView and its model
-
wrote on 13 Nov 2012, 16:37 last edited by
OK, this is bugging me. If I do this:
@MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
DirectorDB = QSqlDatabase::addDatabase("QSQLITE", "test");
DirectorDB.setHostName("localhost");
DirectorDB.setDatabaseName("DirectorConfig.db");
DirectorDB.open();QSqlQueryModel model; model.setQuery("select * from profiles;", QSqlDatabase::database("test")); ui->tableView->setModel( &model );
}@
It does not populate the tableView. It DOES give me the top-left corner thing. If I alter the SQL to reference a non-existent table, I don't get the top-left corner thing so I know it's finding the DB and finding the table, it's just not populating the tableView.
If I do this:
@int main( int argc, char * * argv )
{
QApplication app( argc, argv );QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE", "test" ); db.setDatabaseName( databaseName ); db.open(); QSqlQueryModel model; model.setQuery( "select * from profiles;", QSqlDatabase::database( "test" ) ); QTableView view; view.setWindowTitle( "Test" ); view.setModel( &model ); view.show(); return( app.exec() );
}@
It works fine. What is the difference between the two other than the fact that I've put the tableView into a properly developed form?
-
wrote on 14 Nov 2012, 00:28 last edited by
I have confirmed that the one I created in QT Creator does know about the SQL connection. I can change the query to "select * from prxxxxofiles;" (obviously broken) and it does not give me any kind of table inside the tableView (ie the top-left click button). If I use a valid table, I do, indeed, get that button up there.
-
wrote on 14 Nov 2012, 00:58 last edited by
model is allocated locally by the constructor, so it is deleted at the end of that function.
As you may need to access the model elsewhere, it should probably be added as a member of that class anyway.
-
wrote on 14 Nov 2012, 01:09 last edited by
Hah! Got it.
Moved:
QSqlQueryModel model;To the MainWindow definition. It was going out of scope when the init method was done.
-
wrote on 14 Nov 2012, 01:13 last edited by
Looks like alexisdm posted the solution while I was eating dinner having an epiphany. Thanks for the answer. That was exactly it.
3/5