【问题标题】:Qtreewidget item change color to Icon in QtreewidgetitemQtreewidget 项目在 Qtreewidgetitem 中将颜色更改为图标
【发布时间】:2018-05-04 20:37:51
【问题描述】:
如何动态更改 qtreewidgetitem 内的背景图标:
一些代码示例..
if item.text(0)=="INL"
item.icon(0).setBackground(Qt.green)
else:
item.icon(0).setBackground(Qt.yellow)
我只想要图标背景而不是所有项目(图标+文本)..
【问题讨论】:
标签:
qt
qtreewidgetitem
qicon
【解决方案1】:
使用delegate item 并覆盖paint 方法。
例子
h 文件
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);
}
要将项目设置为您的表格,请使用setItemDelegateForColumn