将颜色设置为QTableView行

Tin*_*neo 8 qt qt4 qtableview qsqltablemodel

void MyWindow::initializeModelBySQL(QSqlQueryModel *model,QTableView *table,QString sql){
        model = new QSqlQueryModel(this);
        model->setQuery(sql);
}
Run Code Online (Sandbox Code Playgroud)

使用此方法,我可以将QSQlQueryModels设置为我的QTableviews.

但是如何根据单元格值将颜色设置为一行?

ale*_*sdm 25

视图根据Qt::BackgroundRole单元格的角色绘制背景,该角色是该角色QBrush返回的值QAbstractItemModel::data(index, role).

您可以继承子类QSqlQueryModel以重新定义data()以返回您计算的颜色,或者如果您有Qt> 4.8,则可以使用QIdentityProxyModel:

class MyModel : public QIdentityProxyModel
{
    QColor calculateColorForRow(int row) const {
        ...
    }

    QVariant data(const QModelIndex &index, int role)
    {
        if (role == Qt::BackgroundRole) {
           int row = index.row();
           QColor color = calculateColorForRow(row);           
           return QBrush(color);
        }
        return QIdentityProxyModel::data(index, role);
    }
};
Run Code Online (Sandbox Code Playgroud)

并在视图中使用该模型,将sql模型设置为source QIdentityProxyModel::setSourceModel.

要么

您可以保持模型不变,并使用视图上的委托设置修改背景QAbstractItemView::setItemDelegate:

class BackgroundColorDelegate : public QStyledItemDelegate {

public:
    BackgroundColorDelegate(QObject *parent = 0)
        : QStyledItemDelegate(parent)
    {
    }
    QColor calculateColorForRow(int row) const;

    void initStyleOption(QStyleOptionViewItem *option,
                         const QModelIndex &index) const
    {
        QStyledItemDelegate::initStyleOption(option, index);

        QStyleOptionViewItemV4 *optionV4 =
                qstyleoption_cast<QStyleOptionViewItemV4*>(option);

        optionV4->backgroundBrush = QBrush(calculateColorForRow(index.row()));
    }
};
Run Code Online (Sandbox Code Playgroud)

因为从C++代码翻译的最后一种方法并不总是显而易见的,所以这里是python中的等价物:

def initStyleOption(self, option, index):
    super(BackgroundColorDelegate,self).initStyleOption(option, index)
    option.backgroundBrush = calculateColorForRow(index.row())
Run Code Online (Sandbox Code Playgroud)