问题
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