user3578367
user3578367

Reputation: 33

How can I set the background color of some special row in QTableView?

I read an older post however that is not work for me.

I would like to set the background color of every row whose 6th argument is true. I tried to overwrite the Paint method in my subclass of QSqlRelationalDelegate but apparently it does not do anything.

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);
}

How can I fix it?

Upvotes: 1

Views: 824

Answers (1)

fruitCoder
fruitCoder

Reputation: 77

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);
}

Upvotes: 1

Related Questions