I am trying to get to grips with how you display data from a database into a Qt table. What I want to do is change the displayed value on a boolean to read “PASS” or “FAIL” and then change the row colour depending on this.
I have created an QSqlQueryModel derived class for the model and overrode the function:
QVariant TestResultsViewModel::data(const QModelIndex &index, int role) const
{
QVariant value = QSqlQueryModel::data(index, role);
if (value.isValid() && role == Qt::DisplayRole){
switch(index.column()){
case 0:
return value.toBool() ? "PASS" : "FAIL";
}
}
if (role == Qt::TextColorRole){
// Get column 0
QVariant pass = index.sibling(index.row(), 0).data();
if (pass.isValid()){
if (pass.toBool()){
return QVariant::fromValue(QColor(Qt::blue));
}
else{
return QVariant::fromValue(QColor(Qt::red));
}
}
}
return value;
}
But what seems to happen is that the first part is done first and thereafter the values of the column are “PASS” or “FAIL” and not 0, 1 so the colours aren’t changing.
So how should I really be doing this?
The implementation of QModelIndex::data() explains this behaviour:
where m is the model of the model index.
This means your call of
ends up calling
TestResultsViewModel::data()again, meaning you indeed get “PASS” or “FAIL” as a result.In order to avoid this, you can do the following:
This will explicitly call
QSqlQueryModel::data()instead ofTestResultsViewModel::data()and skip your code