0

我想突出显示(通过定义自定义 css)一些项目(QListWidgetItemQListWidgetItem

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

对此有什么办法?

4

1 回答 1

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);
于 2016-05-30T17:05:08.570 回答