QComboBox with icons but no text - how?



  • I want to have QComboBox populated with QIcon items, nothing else, and I would like them to be centered. Problem is, the constructor asks for QString too, which is placed to the right of the corresponding QIcon.

    void QComboBox::addItem(const QIcon & icon, const QString & text, const QVariant & userData = QVariant())
    

    Even if I use an empty QString, I don't see a way to center the icon as only text alignment role is what I see in documentation. QIcon always stays on the left.

    comboBox->setItemData(i, Qt::AlignCenter, Qt::TextAlignmentRole);
    

    There must be a way to do this but I can't find it. Any help?
    Thanks.


  • Qt Champions 2016

    @wavelike
    Hello, I'm not aware of any way besides setting an item delegate. You may want to try that.

    Kind regards.



  • Hi kshegunov,

    That crossed my mind, but I was hoping there would be a simple way to do it as what I am asking for seems very standard.
    I guess setting up an item delegate is what I should do then.

    Thanks.


  • Moderators

    @wavelike said:

    what I am asking for seems very standard

    I guess that's debatable. I don't think I ever saw any app doing that and I would not call it standard.
    Anyway, a delegate is the right thing to do here e.g.

    struct Delegate: public QStyledItemDelegate {
        Delegate(QObject* parent = nullptr) : QStyledItemDelegate(parent) {}
        void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
            auto o = option;
            initStyleOption(&o, index);
            o.decorationSize.setWidth(o.rect.width());
            auto style =  o.widget ? o.widget->style() : QApplication::style();
            style->drawControl(QStyle::CE_ItemViewItem, &o, painter, o.widget);
        }
    };
    


  • @Chris-Kawa

    Thanks Chris, a lot, that is very helpful.

    I was thinking of e.g. drawing applications - don't they use QComboBox-like widgets to offer different colors, brush thickness etc? Those never have any text in them. I might be wrong though as I rarely use them.


  • Moderators

    @wavelike said:

    don't they use QComboBox-like widgets to offer different colors, brush thickness etc?

    Hm, I guess that's true, but I'd say it has more to do with QMenus and QToolButtons than QComboBox. But then again they are indeed similar in some ways. Oh well, the important thing is it's doable and quite easy ;)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.