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

4

我正在使用QTableView和QStandardItemModel,并尝试着对一行进行颜色标记,使字体仍保持黑色。

我在使用委托类的paint方法:

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

3
不需要使用委托,只需尝试使用QStandardItem::setData()函数,使用Qt::FontRoleQt::BackgroundColorRole角色。 - vahancho
它并不使文本透明,因为你的实现什么也没做。你的类Delegate继承了一些有用的东西吗? - Marek R
我已经添加了一个drawDisplay()函数,与fillRect()一起使用,它似乎可以做到我想要的,即绘制背景并保持文本为黑色。 - ethane
再说一遍:你根本没有绘制任何文本,委托方法应该这样做!最好的解决方案是使用现有的实现,并仅更改一些数据!再说一遍:委托继承了什么? - Marek R
3个回答

7

您的Delegate应该继承QStyledItemDelegate

您的paint事件可能应该像这样:

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

5
正如 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));

太好了。在简单的情况下确实不需要委托!谢谢 - Johann Horvat

2
这个对我有用:
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;
    }
};

然后在 main() 函数中将委托分配给表格视图,如下所示:
for(int c = 0; c < ui->tableView->model()->columnCount(); c++)
{
    ui->tableView->setItemDelegateForColumn(c, new TableViewDelegateWritable(ui->tableView));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接