I am using the following stylesheet on a QTreeWidget to change the items style:
QTreeWidget::item
{
padding-left:10px;
padding-top: 1px;
padding-bottom: 1px;
border-left: 10px;
}
After that, I am trying to use the following code to change the color of some specific cells:
// item is a QTreeWidgetItem
item->setBackgroundColor(1, QColor(255, 129, 123));
But the color is not changing. I then discovered that, if I remove the stylesheet from the QTreeWidget, then the color change works.
Any idea how to make the background color change to work keeping the stylesheet?
Use a custom delegate to paint your items instead of stylesheets.
Reimplement the paint()
method to control the way how are the items drawn:
class CMyDelegate : public QStyledItemDelegate
{
public:
CMyDelegate(QObject* parent) : QStyledItemDelegate(parent) {}
void CMyDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex & index) const override;
}
void CMyDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
QStyleOptionViewItemV4 itemOption(option)
initStyleOption(&itemOption, index);
itemOption.rect.adjust(-10, 0, 0, 0); // Make the item rectangle 10 pixels smaller from the left side.
// Draw your item content.
QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &itemOption, painter, nullptr);
// And now you can draw a bottom border.
painter->setPen(Qt::black);
painter->drawLine(itemOption.rect.bottomLeft(), itemOption.rect.bottomRight());
}
And this is how to use your delegate:
CMyDelegate* delegate = new CMyDelegate(tree);
tree->setItemDelegate(delegate);
More documentation here: http://doc.qt.io/qt-5/model-view-programming.html#delegate-classes