c++qtqt5qtableviewqsqlrelationaltablemodel

QSqlRelationalTableModel QTableView colorizing rows


What is the right way to color-code rows in a QTableView?

I'm developing a spreadsheet application that should color-code its rows based on a specific value set in one of the columns. I use QSqlRelationalTableModel and QSqlRelationalDelegate; because, the value that should determine the color is a foreign key.

Why can't it be as simple as the following? Any ideas?

model->setData( model->index( index.row(), index.column() ), 
                QBrush(Qt::red),
                Qt::BackgroundRole );

Solution

  • You should overwrite the data function of QSqlRelationalTableModel and when you get the Qt :: BackgroundRole role to filter according to your case and return the appropriate QBrush, in the following example filter by the foreign field and check that it is equal to Lima:

    Example:

    sqlrelationaltablemodel.h

    #ifndef SQLRELATIONALTABLEMODEL_H
    #define SQLRELATIONALTABLEMODEL_H
    
    #include <QSqlRelationalTableModel>
    
    class SqlRelationalTableModel : public QSqlRelationalTableModel
    {
        Q_OBJECT
    public:
        SqlRelationalTableModel(QObject * parent = 0, QSqlDatabase db = QSqlDatabase());
    
         QVariant data(const QModelIndex & item, int role = Qt::DisplayRole) const;
    };
    
    #endif // SQLRELATIONALTABLEMODEL_H
    

    sqlrelationaltablemodel.cpp

    #include "sqlrelationaltablemodel.h"
    
    #include <QBrush>
    
    SqlRelationalTableModel::SqlRelationalTableModel(QObject *parent, QSqlDatabase db)
        :QSqlRelationalTableModel(parent, db)
    {
    
    }
    
    QVariant SqlRelationalTableModel::data(const QModelIndex &item, int role) const
    {
        if(role == Qt::BackgroundRole)
            if(QSqlRelationalTableModel::data(index(item.row(), 2), Qt::DisplayRole).toString().trimmed() == "Lima")
                            return QVariant(QBrush(Qt::red));
        return QSqlRelationalTableModel::data(item, role);
    }
    

    Output:

    enter image description here

    The complete example can be found here.