Reputation: 55
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?
Upvotes: 1
Views: 2962
Reputation: 147
In Qt 6, an easier solution is to use brushes to apply colors to a QTreeWidgetItem.
You need to create a QBrush with a QColor representing the color you want and apply this QBrush to your item. This will not prevent the stylesheet from modifying the items.
QTreeWidget* tree;
QTreeWidgetItem* item = new QTreeWidgetItem(tree, QStringList("col1", "col2"));
QBrush yellowBrush{ QColor(0xffff00) };
QBrush blueBrush{ QColor(0, 0, 255) };
item->setForeground(0, yellowBrush);
item->setBackground(1, blueBrush);
This method is used by Qt to create the ui_filename.cpp
file from the corresponding filename.ui
form file.
https://doc.qt.io/qt-6/qtreewidgetitem.html#setBackground
Upvotes: 0
Reputation: 2210
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
Upvotes: 2