QT QSqlTableModel - background color in a given data column

你说的曾经没有我的故事 提交于 2019-12-11 19:31:40

问题


I have a tableView example:

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:

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?


回答1:


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.



来源:https://stackoverflow.com/questions/22273260/qt-qsqltablemodel-background-color-in-a-given-data-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!