QTreeWidgetItem 颜色

问题描述 投票:0回答:2

我在 QTreeWidget 上使用以下样式表来更改项目样式:

QTreeWidget::item
{
    padding-left:10px;
    padding-top: 1px;
    padding-bottom: 1px;
    border-left: 10px;
}

之后,我尝试使用以下代码来更改某些特定单元格的颜色:

// item is a QTreeWidgetItem
item->setBackgroundColor(1, QColor(255, 129, 123));

但是颜色没有改变。然后我发现,如果我从 QTreeWidget 中删除样式表,那么颜色更改就会起作用。

知道如何更改背景颜色以保持样式表正常工作吗?

qt qt5 qtreewidget qtreewidgetitem
2个回答
2
投票

使用自定义委托来绘制您的项目而不是样式表。

重新实现

paint()
方法来控制项目的绘制方式:

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());
}

这就是如何使用你的委托:

CMyDelegate* delegate = new CMyDelegate(tree);
tree->setItemDelegate(delegate);

更多文档在这里:http://doc.qt.io/qt-5/model-view-programming.html#delegate-classes


0
投票

在 Qt 6 中,更简单的解决方案是使用画笔将颜色应用于 QTreeWidgetItem。

您需要创建一个 QBrush,其中 QColor 代表您想要的颜色,并将此 QBrush 应用于您的项目。这不会阻止样式表修改项目。

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);

Qt 使用此方法从相应的

ui_filename.cpp
表单文件创建
filename.ui
文件。

https://doc.qt.io/qt-6/qtreewidgetitem.html#setBackground

© www.soinside.com 2019 - 2024. All rights reserved.