2016-05-30 9 views
0

(カスタムCSSを定義する)、QListWidgetItemのいくつかのアイテム(QListWidgetItem)を使用したいと思います。QSSクラスを特定のQListWidgetItemで使用する

QListWidgetItemQWidgetから継承していないので、私はCSSクラスを定義することができるsetPropertyメソッドはありません。

これにはどのようなアプローチがありますか?

答えて

0

あなたはQStyledItemDelegateクラスから継承し、例えば、paint方法を再実装することができます

カスタムデリゲートクラス.H:

#include <QStyledItemDelegate> 
#include <QPainter> 

class SomeItemDelegate : public QStyledItemDelegate 
{ 
    Q_OBJECT 
public: 
    explicit SomeItemDelegate(QObject *parent = 0){} 
    ~SomeItemDelegate(){} 
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; 

signals: 

public slots: 
}; 

カスタムデリゲートクラス.CPP:

void SomeItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const 
{ 

    bool isSelected = option.state & QStyle::State_Selected; 
    bool isHovered = option.state & QStyle::State_MouseOver; 
    bool hasFocus = option.state & QStyle::State_HasFocus; 

    if(index.data(Qt::UserRole) == "custom") { 
     if(isHovered) 
      painter->fillRect(option.rect, QColor(0,184,255,40)); 
     if(isSelected) 
      painter->fillRect(option.rect, QColor(0,184,255,20)); 
     if(!hasFocus) 
      painter->fillRect(option.rect, QColor(144,222,255,5)); 
    } 

    painter->save(); 
    painter->setRenderHint(QPainter::Antialiasing, true); 
    painter->drawText(option.rect, Qt::AlignLeft, index.data().toString()); 
    painter->restore(); 
} 

y我々のQListWidgetロジック:

QListWidget *listW = new QListWidget(this); 
QListWidgetItem *item = new QListWidgetItem(tr("Custom Text")); 
item->setData(Qt::UserRole, "custom"); 
QListWidgetItem *item2 = new QListWidgetItem(tr("Simple Text")); 
listW->addItem(item); 
listW->addItem(item2); 

SomeItemDelegate *del = new SomeItemDelegate(); 
listW->setItemDelegate(del); 
関連する問題