您应该覆盖 QSqlRelationalTableModel 的数据函数,并且当您获得 Qt :: BackgroundRole 角色以根据您的情况进行过滤并返回适当的 QBrush 时,在以下示例中按外部字段过滤并检查它是否等于Lima:
例子:
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);
}
输出:
完整的例子可以在这里找到。