PDA

View Full Version : problems with setting QSqlTableModel in a custom slot



szisziszilvi
17th June 2011, 10:11
Hello,

My problem is that I want to set a tableView in a slot, but its working depends on the place where I add the line "model = new QSqlTableModel;". Detailed below.

I have a small program that connects to a database, reads some simple sql commands from a file, executes that and the result shall be shown on a QTableView widget placed on the MainWindow's gui.
In order to being able to reach it easily I added a (private) member variable to the MainWindow class: QSqlTableModel *model;
I also have a QPushButton (pushButton) on the gui and I added a slot (setTV) to the MainWindow class that can receive its "clicked()" signal. This slot will make the tableView show a chosen table in my database.
In codes speaking I have:


MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
model = new QSqlTableModel; // --- FIRST ---
connect(ui->pushButton, SIGNAL(clicked()),this,SLOT(setTV()));

if(!createConnection()) // this creats the connection
{
ui->labelStatus->setText("no connection");
}else
{
QSqlQuery query;
QFile qfi(":/sql/res/test.sql"); // for testing
QString sqltext;
if(qfi.open(QIODevice::ReadOnly | QIODevice::Text))
{
while(!qfi.atEnd())
{
sqltext.append(qfi.readLine());
}
}
query.exec(sqltext);
}

}

void MainWindow::setTV()
{
model = new QSqlTableModel; // --- SECOND ---
model->setTable("todel");//my test table name is "todel"
model->select();

ui->tableView->setModel(model);
}


In the code above I indicated the two places, FIRST and SECOND. If the very same line is on the first place, the tableview does not show anything. If it is on the SECOND place instead, it works. However I would prefer the first place as model should be deleted in the destructor and futrhermore that would have no sense executing a "model = new QSqlTableModel;" comamnd whenever one clicks the button.

So the question is: why does it not work if the model's line is on the FIRST place?