C++ 如何设置QTableView中某些特殊行的背景色?

C++ 如何设置QTableView中某些特殊行的背景色?,c++,qt,colors,row,qt5,C++,Qt,Colors,Row,Qt5,我读了一篇老文章,但这对我来说并不适用 我想设置第6个参数为真的每一行的背景色。 我试图覆盖QSqlRelationalDelegate子类中的Paint方法,但显然它没有做任何事情 MoviesDelegate::MoviesDelegate(QObject *parent) : QSqlRelationalDelegate(parent) { } void MoviesDelegate::paint(QPainter *painter,

我读了一篇老文章,但这对我来说并不适用

我想设置第6个参数为真的每一行的背景色。 我试图覆盖QSqlRelationalDelegate子类中的Paint方法,但显然它没有做任何事情

MoviesDelegate::MoviesDelegate(QObject *parent)
    : QSqlRelationalDelegate(parent)
{ }

void MoviesDelegate::paint(QPainter *painter,
                           const QStyleOptionViewItem &option,
                           const QModelIndex &index) const
{
    if( index.sibling( index.row(), 6 ).data().toBool() )
    {
        QStyleOptionViewItemV4 optionViewItem = option;
        optionViewItem.backgroundBrush = QBrush( Qt::yellow );

        drawDisplay( painter, optionViewItem,
                     optionViewItem.rect,index.data().toString() );
        drawFocus( painter, optionViewItem, optionViewItem.rect);
    }
    else
        QSqlRelationalDelegate::paint(painter, option, index);
}

如何修复它?

为什么不使用QbstractItemModel::data和Qt::BackgroundRole作为第二个参数?不应该使用QItemDelegate在QbstractItemView中显示普通数据。它仅用于编辑器小部件。如果希望在视图中使用自定义格式,则应将数据从模型传回。如果视图不能处理某些角色,那么您应该自定义视图。委托仅用于编辑器,编辑器只是编辑时使用的临时小部件,然后被销毁。如果您不想或由于某种原因不能使用视图基础模型的Qt::BackgroundRole,则可以创建一个中间代理模型,该模型将为需要高亮显示的行返回适当的颜色
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    // Grab cell value and cast it to boolean
    bool boolValue = index.model()->data(index).toBool();

    // Paint cell background depending on the bool value
    if(boolValue)
        painter->fillRect(option.rect, QColor(179, 229, 255));
    else
        painter->fillRect(option.rect, Qt::red);

    // Paint text
    QStyledItemDelegate::paint(painter, option, index);
}