Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override Text in QStyledItemDelegate for QTreeView

Tags:

c++

qt

I'm having an issue with overriding the text displayed for a QTreeView using a QStyledItemDelegate. When some condition is met following code is executed:

void MyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
  .
  .

        QStyleOptionViewItemV4 opt = option;
        initStyleOption(&opt, index);
        QString text = opt.text;
        text = text + QString("TEST");
        opt.text = text;

        QStyledItemDelegate::paint(painter, opt, index);
}

I confirmed in the debbugger that TEST is added to opt.text.
However, when I run my program and look at the TreeVuew it is still displaying the original text without the TEST string appended.

It seems that when I call QStyledItemDelegate::paint(painter, opt, index), it's ignoring the change I've made to the opt parameter.

like image 779
JonF Avatar asked Oct 19 '22 18:10

JonF


1 Answers

The default implementation of the QStyledItemDelegate::paint() method uses it's own QStyleOptionViewItem instance initialized with data from the model.

From the Qt 5.4.0 source code:

void QStyledItemDelegate::paint(QPainter *painter,
        const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_ASSERT(index.isValid());

    QStyleOptionViewItem opt = option;
    initStyleOption(&opt, index);

    const QWidget *widget = QStyledItemDelegatePrivate::widget(option);
    QStyle *style = widget ? widget->style() : QApplication::style();
    style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, widget);
}

Solution:

Do not call the default implementation and implement your delegate's paint() method like this:

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

    initStyleOption(&itemOption, index);
    itemOption.text = "Test Text";  // override text

    QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &itemOption, painter, nullptr);
}
like image 171
Tomas Avatar answered Oct 21 '22 15:10

Tomas