PDA

View Full Version : QSqlTableModel doesn't works as an object, but works as a pointer



borisbn
5th July 2011, 20:18
My colleague found a next problem with QSqlTableModel:

#define VARIANT_1
class SomeClass : public QWidget
{
Q_OBJECT

public:

SomeClass(QWidget *parent = 0, Qt::WFlags flags = 0)
{
ui.setupUi(this);

db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
if (!db.open()) {
return;
}

QSqlQuery query;
query.exec("create table person (id int primary key, "
"firstname varchar(20), lastname varchar(20))");
query.exec("insert into person values(101, 'Danny', 'Young')");
query.exec("insert into person values(102, 'Christine', 'Holand')");

#if defined( VARIANT_1 )
p_model = new QSqlTableModel( );
QSqlTableModel & model = *p_model;
#endif
model.setTable("person");
model.setEditStrategy(QSqlTableModel::OnManualSubm it);
model.select();

model.setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
model.setHeaderData(1, Qt::Horizontal, QObject::tr("First name"));
model.setHeaderData(2, Qt::Horizontal, QObject::tr("Last name"));

ui.tableView->setModel(&model);

}

private:
Ui::qhlbClass ui;
QSqlDatabase db;
#if defined( VARIANT_1 )
QSqlTableModel * p_model;
#else
QSqlTableModel model;
#endif
};

if VARIANT_1 is defined tableView shows a right table, else - not.
I.e. if QSqlTableModel comes as an object table doesn't shows it's data...
If QSqlTableModel comes as a pointer it's works fine...
Can you comment this ?

d_stranz
5th July 2011, 20:57
Where have you created an association between your db and your query? You aren't checking the return value of your query exec statements, so you have no idea if they are doing anything at all.

Likewise, where do you create an association between your db and the model? You don't check the return value from select() either, so you don't know that it has failed.

You basically have three totally independent things here, none of them know anything about the others, so it is no wonder that nothing shows up in the view.

borisbn
6th July 2011, 07:46
d_stranz, you are partially right. QSqlTableModel needs a QSqlDatabase in a constructor and uses "default" one if I don't give it. In case of object (not pointer) QSqlTableModel's constructor calling before addDatabase function call, but in case of pointer default db exists. Here is a full answer (http://stackoverflow.com/questions/6587158/qsqltablemodel-doesnt-works-as-an-object-but-works-as-a-pointer)
I didn't check exec() and select() results to reduce code exceptionally. I check it in "urgent" project, certainly :)
Thank you.

ChrisW67
6th July 2011, 07:59
Similar discussion from a couple of days ago.