PDA

View Full Version : Can't update data in QSqlTableModel when the pk Column hidden



topquarck
5th September 2009, 01:32
Hellow there;

I'm trying to view data from a simple DB table to a QtableView.
I used the Sample Code supplied in the QSqlTableModel's Documentation page with a minor modification.
I have a STUDENT table with id pk and name


-- the DB engine is sqlite:
create table student (id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(20) not null);

and i modified the code to be :


model = new QSqlTableModel;
model->setTable("student"); //that's the table name
model->setEditStrategy(QSqlTableModel::OnManualSubmit); // whatever edit strategy, it still not working
model->select();
model->setHeaderData(0, Qt::Horizontal, tr("id"));
model->removeColumn(0); // don't show the ID; <<-- here is the PROBLEM
model->setHeaderData(1, Qt::Horizontal, tr("name"));

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

data is shown and everything is fine. But when I try to update a recoed ' the name field for a given record'; I get a debug message saying :


QSqlQuery::value: not positioned on a valid record

and the rows don't update
If I just commented the removeColumn() line; data updates when I modify them and everything works fine.
BUT I need to remove the ID column - i.e keep it hidden from users - ! it is the PRIMARY KEY and I cant just let users manipulate it :mad:

Is there a way to hide the ID column and still be able to update 'the other column values that are NOT id' ??? :confused:

thanx alot in advance

qteto
21st October 2009, 03:04
hi,
try view->hideColumn(0) instead model-> removeColumn(0)

ChrisW67
21st October 2009, 08:13
Updates require a way to uniquely identify the row to be updated. Removing the unique id makes updates difficult.

Hiding the column is a function of the view, not the model. So, for example,


model = new QSqlTableModel;
model->setTable("student"); //that's the table name
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
model->select();
model->setHeaderData(0, Qt::Horizontal, tr("id")); // will not be shown in view below
model->setHeaderData(1, Qt::Horizontal, tr("name"));

ui->tableView->setModel(model);
ui->tableView->setColumnHidden(0, true); // hide the id from view
ui->tableView->show();