Problems with allocating QSqlTableModel on heap
I have a form with 2 PuchButtons and a TableView created using QTCreator. Now I want to populate TableView with data from SQL database using QSqlTableModel.
My question is: Why when i allocate QSqlTableModel in PushButton1Click everything is ok, and when I allacate it in MainWindow constructor the data from database doesn't show on TableView.
(First I click button 1 to open database, then I click button 2 to fetch data)
Here is declaration of mainwindow class:
Code:
{
Q_OBJECT
public:
~MainWindow();
private:
Ui::MainWindow *ui;
private slots:
bool PushButton1Click();
bool PushButton2Click();
};
Here is code which works:
Code:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow
::MainWindow(QWidget *parent
){
ui->setupUi(this);
// m = new QSqlTableModel(this); // NOT OK !!!!!!!!
}
MainWindow::~MainWindow()
{
delete ui;
}
bool MainWindow::PushButton1Click()
{
db.setHostName("localhost");
db.setDatabaseName("axis");
db.setUserName("root");
db.setPassword("kosa1980");
bool ret = db.open();
return ret;
}
bool MainWindow::PushButton2Click()
{
m->setTable("wagi");
m->select();
m->removeColumn(0);
m
->setHeaderData
(0, Qt
::Horizontal,
QObject::tr("numer_seryjny"));
m
->setHeaderData
(1, Qt
::Horizontal,
QObject::tr("typ"));
ui->tableView->setModel(m);
return true;
}
Here is code which doesn't work:
Code:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow
::MainWindow(QWidget *parent
){
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
bool MainWindow::PushButton1Click()
{
db.setHostName("localhost");
db.setDatabaseName("axis");
db.setUserName("root");
db.setPassword("kosa1980");
bool ret = db.open();
//m = new QSqlTableModel(this); // OK !!!!!!!!
return ret;
}
bool MainWindow::PushButton2Click()
{
m->setTable("wagi");
m->select();
m->removeColumn(0);
m
->setHeaderData
(0, Qt
::Horizontal,
QObject::tr("numer_seryjny"));
m
->setHeaderData
(1, Qt
::Horizontal,
QObject::tr("typ"));
ui->tableView->setModel(m);
return true;
}
Why second version doesn't work?
Re: Problems with allocating QSqlTableModel on heap
Before you create the new model in the c-tor, also set up an default database connection! Then it will work. The model needs a default database connection (if you don't specify anything else...)
EDIT: Even if your password is only for your localhost, it is not a good idea to post it here. (Since most people use a single password for multiple logins and occasions:cool:)