PDA

View Full Version : Reimplement data() in QSqlQueryModel



john_erlandsson
4th January 2012, 23:33
Hi!

I am experimenting with a subclass of QSqlQueryModel. Since I wanted to change the background color in the ListView, I reimplemented the data method


QVariant BrowseWoTableModel::data( const QModelIndex &item, int role ) const
{
if( role == Qt::BackgroundColorRole )
{
return Qt::green;
}

else if( role == Qt::DisplayRole )
{
return record( item.row() ).value( item.column() );
}

return QVariant();
}

This works for setting the background color, but fails in displaying the data.

What am I missing here?

//John

ChrisW67
5th January 2012, 00:20
Your override returns null QVariants for roles like Qt::FontRole, Qt::TextColorRole and Qt::ForegroundRole.

Try something like this:


QVariant BrowseWoTableModel::data( const QModelIndex &item, int role ) const
{
if (!item.isValid())
return QVariant();

if( role == Qt::BackgroundColorRole )
return Qt::green;
else
return QSqlQueryModel::data(item, role);
}

john_erlandsson
5th January 2012, 00:22
The "similar threads" box held the anwser.


QVariant BrowseWoTableModel::data( const QModelIndex &item, int role ) const
{
QVariant ret = QSqlQueryModel::data( item, role );

if( role == Qt::BackgroundColorRole )
{
return Qt::green;
}

return ret;
}

This works. But i dont understand why. Where does the data come from?

ChrisW67
5th January 2012, 03:36
Line 3 gathers the result you would received from a base QSqlQueryModel and that is returned unless the role is BackgroundColorRole.