PDA

View Full Version : Access data from QSqlTableModel



qlands
5th July 2011, 15:19
Hi,

I am very raw with model/view hence the many questions..

On my QSqlTableModel I have the following code to present the data:



QVariant maintModel::data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole)
{
QString var;
var = record(index.row()).value("cnty_nam").toString();
qDebug() << index.row() << displayColumnCode << var;
return var;
}
return QVariant();
}


I am just displaying one column thus I just use row. From the debug I can see that the row numbers are fine, also the column exists, but in this case var is always empty! because record(index.row()).value("cnty_nam").isValid() is always false!!!

I initialize the model with:



m_mainmodel = new maintModel(this,db);
m_mainmodel->setTable("country");
m_mainmodel->setEditStrategy(QSqlTableModel::OnManualSubmit);
if (m_mainmodel->select())
{
ui->ListView1->setModel(m_mainmodel);
}


For sure is something very silly... but I don't know what is happening!!!

Thanks,
Carlos.

mcosta
5th July 2011, 15:39
One question:

"Why are you re-implementing this function?"

You can use QSqlTableModel as it is.

qlands
5th July 2011, 15:45
Well I have more than the display role. For example I need to display a different pixmap based on some extra data attached to every record (that is not stored in the database). I use this under Qt::DecorationRole. That's why i am reimplementing this.

mcosta
5th July 2011, 16:16
Ok,

I suggest you to call the parent implementation when you have to fetch data and add your code only to get information specific to your implementation.



QVariant maintModel::data(const QModelIndex &index, int role) const
{
QVariant result;
if (role == Qt::DecorationRole) {
// Your code
}
else
result = QSqlTableModel::data(index, role);

return result;
}

qlands
5th July 2011, 16:23
Yep!!!.

Many thanks,
Carlos