class Delegate : public QStyledItemDelegate{ Q_OBJECTpublic: Delegate(){} void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (option.state & QStyle::State_Selected) { QVariant var = index.model()->data(index, Qt::UserRole); painter->setPen(QColor(Qt::white)); // это не обязательно painter->fillRect(option.rect, var.value<QColor>()); painter->drawText(option.rect, index.model()->data(index, Qt::DisplayRole).toString()); } else QStyledItemDelegate::paint(painter, option, index); }};
ui.listWidget->setItemDelegate(new Delegate());
QColor color = getMyData() ? QColor(Qt::darkGreen) : QColor(Qt::darkBlue);myItem->setData(Qt::UserRole, color);
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const{ QStyleOptionViewItem myOpt(option); if (option.state & QStyle::State_Selected) { QPalette pal(myOpt.palette); QVariant var = index.model()->data(index, Qt::UserRole); pal.setColor(QPalette::Highlight,var.value<QColor>()); myOpt.palette = pal; } QStyledItemDelegate::paint(painter, myOpt, index);}
QListView { color: rgb(127, 0, 63); background-color: rgb(255, 255, 241); selection-color: white; selection-background-color: rgb(191, 31, 0);}