How do i add an icon to QComboBox in Qt?

You can simply do (Qt5), for example:

   QIcon icon = QIcon::fromTheme("edit-undo");
   QString label = "foo";
   combo->addItem( icon, label );

Update: based on Qt 5.13 (released 2019) there us a dedicated API for this:

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

Or if you want to specify an index:

void QComboBox::insertItem ( int index, const QString & text)
void QComboBox::setItemIcon ( int index, const QIcon & icon )

All credit for this update goe to user Soyal7 who suggested the edit. The former response, which still applies especially for older versions, was:

You can use the following APIs:

void QComboBox::insertItem ( int index, const QString & text, const QVariant & userData = QVariant() )
void QComboBox::setItemIcon ( int index, const QIcon & icon )

http://doc.qt.io/qt-5/qcombobox.html#insertItem
http://doc.qt.io/qt-5/qcombobox.html#setItemIcon

As for the code snippet it's as easy as this:

void AddItem(QComboBox* combo, QString itemName, QIcon* icon)
{
    combo->insertItem(0, itemName);
    combo->setItemIcon(0, *icon);
}

Tags:

C++

Qt