PDA

View Full Version : How to fill an inserted column with data?



croo
12th December 2010, 17:22
Hello everyone.

I want to insert a new column in a model, then fill it up with data.
The problem below is the simplified one: The model already contains 5 column from a database, filled with data.
All it want to do is insert a column, and fill each new index with the string "BLA".

The model is a QSqlTableModel.


void ReadersRoom::doPaidColumn()
{
model->insertColumn(5);
model->setHeaderData(5,Qt::Horizontal,trUtf8("Paid"));
QString s = "BLA";

for(int i = 0; i < model->rowCount(); ++i)
{
QModelIndex index = model->index(i,5);
if(index.isValid()) // index is valid.
model->setData(index,s); // returns TRUE.
QString test = model->index(i,5).data().toString(); // STRING IS EMPTY!
}
}


The result(on a tableview):
the new column is there and it contains nothing.

If I try to rewrite the 4th column with this method it works fine. But the setData won't put any data in the newly added column.

What am I doing wrong?

wysota
12th December 2010, 17:44
You can't insert columns into the database like that. insertColumn() may even work but the QSqlRecord that operates on the data in the model knows nothing of your new column so it can't return data for it. It's even probably setData() returns false denoting that the operation has failed.

croo
12th December 2010, 19:42
I rechecked and setData() returns true.
My goal is to make a computed column of something related to that database and display it.
I'm not at all trying to modify the underlying database..

My plan was to load the desired table from the database to a model, display it, then add one more column to the model, and fill it with whatever I want(it was like this in ado.Net). Your reply suggest that there is a stronger connection between the db and the model.
I recently started to learn the model/view part of Qt and probably went the wrong way....

So how can I do something like this?

wysota
12th December 2010, 19:58
I rechecked and setData() returns true.
My goal is to make a computed column of something related to that database and display it.
I'm not at all trying to modify the underlying database..
So either subclass the model or implement a proxy model for your database model. A cleaner approach would be to use a proxy although it's probably a bit (just a bit) more work.