将颜色设置为 QTableView 行 [英] Set color to a QTableView row

查看:91
本文介绍了将颜色设置为 QTableView 行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

使用这种方法,我可以为我的 QTableviews 设置 QQlQueryModels.

With this method i can set a QSQlQueryModels to my QTableviews.

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

But How i can set color to a row based on a cell value?

推荐答案

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

The view draws the background based on the Qt::BackgroundRole role of the cell which is the QBrush value returned by QAbstractItemModel::data(index, role) for that role.

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

You can subclass the QSqlQueryModel to redefine data() to return your calculated color, or if you have Qt > 4.8, you can use a 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);
    }
};

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

And use that model in the view, with the sql model set as source with 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()));
    }
};

由于从 C++ 代码转换过来的最后一种方法并不总是显而易见的,这里是 Python 中的等效方法:

As the last method is not always obvious to translate from C++ code, here is the equivalent in python:

def initStyleOption(self, option, index):
    super(BackgroundColorDelegate,self).initStyleOption(option, index)
    option.backgroundBrush = calculateColorForRow(index.row())

这篇关于将颜色设置为 QTableView 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆