qtqtreewidgetitemqicon

Qtreewidget item change color to Icon in Qtreewidgetitem


how change background icon inside a qtreewidgetitem dinamically: Some code example..

if item.text(0)=="INL"
   item.icon(0).setBackground(Qt.green)
else:
   item.icon(0).setBackground(Qt.yellow) 

I want only icon background not all item (icon+text).. test


Solution

  • Use delegate item and override the paint method.

    Example

    h file

    class MyItemDelegate : public QItemDelegate
    {
    public:
       MyItemDelegate(QObject *parent = Q_NULLPTR);
       void paint ( QPainter * painter, const QStyleOptionViewItem & oStyleOption, const QModelIndex & index ) const;
    
    }
    

    cpp

    void MyItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &oStyleOption, const QModelIndex &index) const
    {
        // Apply for column 0
        if (index.column() == 0) {  
    
           // background color
           Qt::GlobalColor eColor;
    
           // Get table data
           if (index.model()->data(index).toString() == "INL")
               eColor = Qt::green;
           else
               eColor = Qt::yellow;
    
           painter->save();
    
           // background rect size (icon size 16x16 + padding)
           QRect oRect(oStyleOption.rect.x() + 2, oStyleOption.rect.y() + 6 , 16, 16);
    
           // background color
           painter->fillRect(oRect, eColor);
           painter->restore();    
       }
       return QItemDelegate::paint(painter,oStyleOption,index);
    }
    

    to set the item to your table use setItemDelegateForColumn