Question

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.

Était-ce utile?

La solution

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();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top