Search code examples
qtqt5appearanceqsqltablemodel

Own QSqlTableModel, color whole row based on the value of a QModelIndex


I have extended QSqlTableModel in the past, but currently I'm stuck (still a beginner after all):

QVariant MyChild::data(const QModelIndex &index, int role) const
{
    // Check if (soft)deleted / cancelled
    if(index.column() == 3)
    {
       if(QSqlTableModel::data(index, Qt::DisplayRole).toString() == "1")
       {
           if(role == Qt::DisplayRole)
           {
               return "Deleted";
           }

           if(role == Qt::BackgroundColorRole)
           {
               return QVariant(QColor(Qt::yellow));
           }

          // QSqlTableModel::setData(index, QVariant(QColor(Qt::red)), Qt::BackgroundColorRole);
      //     setData(index, QColor(Qt::red), Qt::BackgroundColorRole);
       }
    }

   return QSqlTableModel::data(index, role);
}

Now this works great for what it does. It colors the field in the table yellow, but instead I'd love to have the whole row being colored. So you can see at one glimpse that this record was (soft) deleted already.

As you can see, I already tried with calling setData, but to no avail. (Of course I would do this for each index in the this very row, but as it doesn't work to begin with I stopped there.)

Any ideas on this? I searched the web a lot, but I can't seem to find a way to color the whole row.


Solution

  • I would do something like that (its not testet at all so adaptions may be needed):

    QVariant MyChild::data(const QModelIndex &index, int role)
    {
        // Check if (soft)deleted / cancelled
        if(role == Qt::DisplayRole && index.column() == 3 && QSqlTableModel::data(index, Qt::DisplayRole).toString() == "1")
        {
            return "Deleted";
        }
        else if(role == Qt::BackgroundColorRole)
        {
            QModelIndex tmpIdx = QSqlTableModel::index(index.row(), 3, index.parent());
            if(QSqlTableModel::data(tmpIdx, Qt::DisplayRole).toString() == "1")
            {
                return QVariant(QColor(Qt::yellow));
            }
        }
        return data(index, role);
    }
    

    So check for each modelindex if the specified column says that the row is deleted. There would also be no harm in checking if "tmpIdx" is valid...