Älskar
Älskar

Reputation: 2579

QTableView, setting a cell's font and background colour

I am using QTableView and QStandardItemModel and I'm trying to colour a row with the font remaining black.

I am using my delegate class's paint method:

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

This does not work at all and it makes the text within each cell transparent. What am I doing wrong here?

[EDIT] I've used painter->fillRect(option.rect, brush); as well but it makes the cell background and text the same colour.

Upvotes: 4

Views: 19360

Answers (3)

Marek R
Marek R

Reputation: 37607

Your Delegate should inherit QStyledItemDelegate.

Your paint event probably should look like this:

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

Upvotes: 7

fruitCoder
fruitCoder

Reputation: 77

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

Upvotes: 2

Tomas
Tomas

Reputation: 2210

As vahancho suggested, you can use the QStandardItem::setData() function:

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

Or the QStandardItem::setBackground() and QStandardItem::setForeground() functions:

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

Upvotes: 5

Related Questions