在特定的QListWidgetItem上使用QSS类

时间:2016-05-30 16:20:27

标签: qt qtstylesheets qlistwidgetitem

我想突出显示(通过定义自定义css)QListWidgetItem的某些项目(QListWidgetItem)。

由于QListWidgetItem不从QWidget继承,因此没有setProperty方法可以让我定义一个css类。

对此有何看法?

1 个答案:

答案 0 :(得分: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();
}

有些人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);