QTableView,设置单元格的字体和背景颜色

新手上路,请多包涵

我正在使用 QTableView 和 QStandardItemModel 并且我正在尝试用保持黑色的字体为一行着色。

我正在使用我的委托类的绘画方法:

 void Delegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QBrush brush(Qt::red, Qt::SolidPattern);
    painter->setBackground(brush);
}

这根本不起作用,它使每个单元格中的文本透明。我在这里做错了什么?

[编辑] 我也使用过 painter->fillRect(option.rect, brush); 但它使单元格背景和文本颜色相同。

原文由 ethane 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.5k
1 个回答

您的 Delegate 应该继承 QStyledItemDelegate

您的绘画事件可能应该如下所示:

 void Delegate::paint(QPainter *painter,
                     const QStyleOptionViewItem &option,
                     const QModelIndex &index) const
{
    QStyleOptionViewItem op(option);

    if (index.row() == 2) {
        op.font.setBold(true);
        op.palette.setColor(QPalette::Normal, QPalette::Background, Qt::black);
        op.palette.setColor(QPalette::Normal, QPalette::Foreground, Qt::white);
    }
    QStyledItemDelegate::paint(painter, op, index);
}

原文由 Marek R 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题