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

QTableView, setting a cell's font and background colour

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

我正在使用我的委托 class 的绘制方法:

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);,但它使单元格背景和文本颜色相同。

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

按照vahancho的建议,您可以使用QStandardItem::setData()函数:

QStandardItem item;
item.setData(QColor(Qt::green), Qt::BackgroundRole);
item.setData(QColor(Qt::red), Qt::FontRole);

或者 QStandardItem::setBackground()QStandardItem::setForeground() 函数:

QStandardItem item;
item.setBackground(QColor(Qt::green));
item.setForeground(QColor(Qt::red));

This worked for me:

class TableViewDelegateWritable : public QStyledItemDelegate
{
    Q_OBJECT
public:
    explicit TableViewDelegateWritable(QObject *parent = 0)
        : QStyledItemDelegate(parent)
    {
    }

    // background color manipulation
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        QColor background = QColor(135, 206, 255); // RGB value: https://www.rapidtables.com/web/color/blue-color.html
        painter->fillRect(option.rect, background);

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

    // only allow digits
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index ) const
    {
        QSpinBox *editor = new QSpinBox(parent);

        editor->setMinimum(-99999);
        editor->setMaximum(99999);

        return editor;
    }
};

Then in main() assign the delegate to the tableview like this:

for(int c = 0; c < ui->tableView->model()->columnCount(); c++)
{
    ui->tableView->setItemDelegateForColumn(c, new TableViewDelegateWritable(ui->tableView));
}