Skip to content

Use an enum with custom values with QComboBox

Hello world.

Daily coding brings up new opportunities to search for and discover new ways to accomplish things. Perhaps not always the best solutions but, in time, we’re getting there. Today, life brought upon me a new challenge: simplify previously written code. Among other useful thing I will probably mention in future posts, one needed me to insert a enum with custom values in a QComboBox. I’ll jump right to it. Here’s my enum:

<code>enum myEnumeration
    firstElem  = -1,
    secondElem =  2,
    thirdElem  =  3,
    fourthElem =  6

As you can see, I assign custom values to this enum‘s items. Here’s how I added the enum elements to the QComboBox :

<code>QComboBox *comboBox;
comboBox-&gt;addItem("First Element", myEnumeration::firstElem);
comboBox-&gt;addItem("Second Element", myEnumeration::secondElem);
comboBox-&gt;addItem("Third Element", myEnumeration::thirdElem);
comboBox-&gt;addItem("Fourth Element", myEnumeration::fourthElem);

The first parameter is the string that will be displayed in the QComboBox as items. The second parameter is a QVariant variable that represents the item’s data, in this case, an integer.

ATTENTION! The syntax I used to call the enum items is valid only in C++11. Otherwise just call the items directly.

In order to get the data from the items in the QComboBox I used the following:

<code>int i = comboBox-&gt;itemData(comboBox-&gt;currentIndex()).toInt();</code>

This should be pretty easy and straight forward.

Many thank’s to Phlucious for the work done. This helped me get to this solution.

Update I just found that there is a work in progress to simplify the way the data is taken from the QComboBox items. A new method that will replace comboBox->itemData(comboBox->currentIndex()) with comboBox->currentData().

Published inSoftwareTutorials

Be First to Comment

Lasă un răspuns