Search code examples
c++cssqtqtgui

QT QSqlTableModel - background color in a given data column


I have a tableView example:

enter image description here

Like when the data column status is S. The background color of the table would be green and when N would be red.

Example of what I want:

enter image description here

My code:

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
       //Con Db...

        model = new QSqlTableModel(this);
        model->setTable("app");
        model->setEditStrategy(QSqlTableModel::OnManualSubmit);
        model->select();
        model->setHeaderData(0, Qt::Horizontal, tr("number"));
        model->setHeaderData(1, Qt::Horizontal, tr("status"));
        ui->tableView->setModel(model);
}

Could someone help me?


Solution

  • Reimplement, i.e. subclass QSqlTableModel and provide an implementation of the data function as per below. Note that the MySubClassedSqlTableModel implementation needs to be placed in a header file that is MOC'ed (normally automatically done).

      #include <QSqlTableModel>
        class MySubClassedSqlTableModel : public QSqlTableModel
        {
            Q_OBJECT
            public:
               MySubClassedSqlTableModel(QObject * parent = 0, QSqlDatabase db = QSqlDatabase())
               : QSqlTableModel(parent,db) {;}
               QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const
               {
                  if(role==Qt::BackgroundColorRole)
                  {
                     const QVariant value(data(index,Qt::DisplayRole));
                     return QVariant(QColor(value.toString()=="S"?Qt::green:Qt::red));
                  }
                  return QSqlTableModel::data(index,role);
               }
        };
    
        model = new MySubClassedSqlTableModel(this); //<==== use your model
                model->setTable("app");
                model->setEditStrategy(QSqlTableModel::OnManualSubmit);
                model->select();
                model->setHeaderData(0, Qt::Horizontal, tr("number"));
                model->setHeaderData(1, Qt::Horizontal, tr("status"));
                ui->tableView->setModel(model);
    

    Btw subclassing is something you need to do in most cases when you want to customize the behavior.