Вы можете наследовать от класса QStyledItemDelegate
и переопределение paint
метод, например:
Пользовательский класс делегата .Н:
#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);