如何在QTableView中设置一些特殊行的背景色

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

本文关键字:背景色 QTableView 设置      更新时间:2023-10-16

我读了一篇旧的文章,但是这对我来说不起作用。

我想设置其第六个参数为真的每一行的背景颜色。我试图在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);
}

我该如何修复它?

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