Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i add an icon to QComboBox in Qt?

Tags:

c++

qt

I want to add an icon with text into the QComboBox in Qt, how can I implement it?

like image 737
Legend Avatar asked Aug 31 '11 07:08

Legend


2 Answers

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);
}
like image 76
Ioan Paul Pirau Avatar answered Oct 12 '22 12:10

Ioan Paul Pirau


You can simply do (Qt5), for example:

   QIcon icon = QIcon::fromTheme("edit-undo");
   QString label = "foo";
   combo->addItem( icon, label );
like image 33
Paulo Carvalho Avatar answered Oct 12 '22 13:10

Paulo Carvalho