Brain Salad

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:

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

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:

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().