4

I have been looking at the QComboBox source file for a while now and I can't figure out what I need to change so that the icon is positioned above text in a QComboBox.

|-----------------------|
|         -----         |
|         |icn|         |
|         -----         |
|    Text label here    |
-------------------------

The paint method in QCombobox is very simple and references something called QStyleOptionComboBox, but I don't think I want to be making changes here though as this will impact portability.

Would I be better inventing something new to act and behave like a QComboBox?

I should have added that it I am looking at changing both the ListView and selected item i.e the button portion.

1 Answers1

4

In order to handle the icon's (decoration) position in the combo box's pull down view, you need to override its view options QAbstractItemView::viewOptions(). Let's create a custom view and replace the native combo box view with ours:

class ComboView : public QListView
{
protected:
    QStyleOptionViewItem viewOptions() const
    {
        // Set icon on the top and center of combo box item.
        QStyleOptionViewItem option = QListView::viewOptions();
        option.decorationAlignment = Qt::AlignHCenter | Qt::AlignCenter;
        option.decorationPosition = QStyleOptionViewItem::Top;
        option.displayAlignment = Qt::AlignCenter;   
        return option;
    }
};

and for the combo box:

QComboBox cb;
cb.setView(new ComboView); // Sets the custom view.
cb.addItem(QIcon("icon.png"), "Item1");
cb.addItem(QIcon("icon.png"), "Item2");
cb.show();
vahancho
  • 20,808
  • 3
  • 47
  • 55
  • Wow thanks, that works really well for the contents of the drop-down, though this does not affect the selected item? I can only assume that the same style options can be applied to the button portion of QComboBox? – aManFromOuterSpace May 05 '14 at 13:13
  • @aManFromOuterSpace, theoretically yes, but I do not think it will be as easy as for pull down view. The editable part is suppose to be a line edit, so I am not sure I know how to modify it without overriding paint() event etc. – vahancho May 05 '14 at 13:16
  • I thought QCombobox was made up of a push button and a popup? I will keep looking into how to align the button portion in the same way as you so helpfully described. – aManFromOuterSpace May 05 '14 at 13:32
  • Hi! Can you help me. I need hide the text label of the item. This is possible? – Šerg Nov 23 '16 at 06:51
  • @Šerg, what means hide the text label? What if you just set an empty string as a text? – vahancho Nov 23 '16 at 09:01