2016-03-22 34 views
1

私はアイテムのスタイルを変更するにはQTreeWidgetで次のスタイルシートを使用しています:その後QTreeWidgetItem色

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からスタイルシートを削除すると、色の変更が機能することを発見しました。

スタイルシートを維持するために背景色を変更する方法はありますか?

答えて

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

Iをありがとう、ありがとう。今私はそれを理解するためのドキュメントを読む必要があります:) 私は今、問題は 'resizeColumnToContents'がうまくいかないことです。私は問題を見つけ出すかどうか分かります。 – hteso

関連する問題