在QItemDelegate的重新实现的绘制功能中,setFont不起作用

问题描述 投票:0回答:2

我为paint()重新实现了QTreeWidget函数,我想显示第二列粗体的数据,但它不起作用。

我该如何解决?

void extendedQItemDelegate::paint(QPainter *painter,
                                  const QStyleOptionViewItem &option,
                                  const QModelIndex &index) const
{
    const QString txt = index.data().toString();
    painter->save();
    QFont painterFont;
    if (index.column() == 1) {
        painterFont.setBold(true);
        painterFont.setStretch(20);
    }
    painter->setFont(painterFont);
    drawDisplay(painter, option, rect, txt);
    painter->restore();
}

我附了一个屏幕截图的问题,下半场应该是大胆的

c++ qt qtreeview qitemdelegate
2个回答
0
投票

你忘了通过extendedQItemDelegate成员函数将你的QTreeView添加到QTreeWidget / setItemDelegate对象。

举个例子:

QTreeWidget* tree_view = ...;
extendedQItemDelegate* extended_item_delegate = ...;
tree_view->setItemDelegate(extended_item_delegate);

0
投票

您需要复制const QStyleOptionViewItem &option,将字体更改应用于该副本,然后使用您的副本而不是传递给函数的原始option进行绘制。

void extendedQItemDelegate::paint(QPainter *painter,
                                  const QStyleOptionViewItem &option,
                                  const QModelIndex &index) const
{
    const QString txt = index.data().toString();
    painter->save();
    QStyleOptionViewItem optCopy = option;     // make a copy to modify
    if (index.column() == 1) {
        optCopy.font.setBold(true);            // set attributes on the copy
        optCopy.font.setStretch(20);
    }
    drawDisplay(painter, optCopy, rect, txt);  // use copy to paint with
    painter->restore();
}

(刚刚意识到这是一个老问题,但它突然出现在qt标签的顶部。)

© www.soinside.com 2019 - 2024. All rights reserved.