【问题标题】:QTreeWidgetItem colorQTreeWidgetItem 颜色
【发布时间】:2016-07-09 14:27:06
【问题描述】:

我在 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


    【解决方案1】:

    使用自定义委托代替样式表来绘制您的项目。

    重新实现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

    【讨论】:

    • 我已经成功了,谢谢。现在我必须阅读文档才能理解它:) 我现在遇到的问题是resizeColumnToContents 不能正常工作;我看看能不能解决问题。
    猜你喜欢
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 2010-11-07
    • 2020-02-15
    • 1970-01-01
    • 2018-10-29
    相关资源
    最近更新 更多