我想突出显示(通过定义自定义css)QListWidgetItem
的某些项目(QListWidgetItem
)。
由于QListWidgetItem
不从QWidget
继承,因此没有setProperty
方法可以让我定义一个css类。
对此有何看法?
答案 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);