首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >QTreeWidgetItem颜色

QTreeWidgetItem颜色
EN

Stack Overflow用户
提问于 2016-03-22 15:39:41
回答 1查看 2.3K关注 0票数 1

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

代码语言:javascript
复制
QTreeWidget::item
{
    padding-left:10px;
    padding-top: 1px;
    padding-bottom: 1px;
    border-left: 10px;
}

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

代码语言:javascript
复制
// item is a QTreeWidgetItem
item->setBackgroundColor(1, QColor(255, 129, 123));

但颜色并没有改变。然后我发现,如果我从QTreeWidget中删除样式表,那么颜色更改就能工作了。

知道如何使背景色改变以保持样式表的工作吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-22 20:08:38

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

重新实现paint()方法以控制如何绘制项:

代码语言:javascript
复制
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());
}

以下是如何使用您的代表:

代码语言:javascript
复制
CMyDelegate* delegate = new CMyDelegate(tree);
tree->setItemDelegate(delegate);

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36158827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档