QComboBox/QStyledItemDelegate, Icon Size for selected item.
-
I have a QComboBox with a QStyledItemDelegate that shows an icon + text, the icon is sized through the QStyledItemDelegate to be 32x32, when the ComoBox is selected it's doing what I expect when popped up. But, both the default option icon, and when I select an item the icon is much smaller than 32x32 and seems to be reduced to the text height for the combobox item. I'd post an image of what I'm talking about but the spam detector won't let me.
Was hoping someone could give me some clues how to have the selected item be a 32x32 icon with text like the popup shows. Here's the current implementation of my QStyledItemDelegate, using just the standard QComboBox:
class IconComboDelegate : public QStyledItemDelegate { public: IconComboDelegate(QObject* parent = nullptr) : QStyledItemDelegate(parent) {} void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override { if (index.data(Qt::DecorationRole).isValid()) { QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole)); QRect iconRect = option.rect; iconRect.setWidth(32); iconRect.setHeight(32); // Center the icon vertically iconRect.moveTop(option.rect.top() + (option.rect.height() - iconRect.height()) / 2); // Draw the icon icon.paint(painter, iconRect, Qt::AlignCenter, QIcon::Normal, option.state & QStyle::State_Selected ? QIcon::On : QIcon::Off); // Draw the text QRect textRect = option.rect; textRect.setLeft(iconRect.right() + 5); // Use the correct color for selected items if (option.state & QStyle::State_Selected) { painter->setPen(option.palette.color(QPalette::HighlightedText)); } else { painter->setPen(option.palette.color(QPalette::Text)); } painter->drawText(textRect, Qt::AlignVCenter | Qt::AlignLeft, index.data(Qt::DisplayRole).toString()); // Draw the focus rect if needed if (option.state & QStyle::State_HasFocus) { QStyleOptionFocusRect focusOption; focusOption.QStyleOption::operator=(option); focusOption.rect = option.rect; focusOption.state |= QStyle::State_KeyboardFocusChange; focusOption.state |= QStyle::State_Item; QPalette::ColorGroup cg = (option.state & QStyle::State_Enabled) ? QPalette::Normal : QPalette::Disabled; focusOption.backgroundColor = option.palette.color(cg, (option.state & QStyle::State_Selected) ? QPalette::Highlight : QPalette::Window); QApplication::style()->drawPrimitive(QStyle::PE_FrameFocusRect, &focusOption, painter); } } else { QStyledItemDelegate::paint(painter, option, index); } } QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const override { QSize size = QStyledItemDelegate::sizeHint(option, index); return QSize(qMax(size.width(), 36 + 5 + option.fontMetrics.horizontalAdvance(index.data(Qt::DisplayRole).toString())), qMax(size.height(), 36)); } };