Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt: using enums with QComboBox

Tags:

c++

combobox

qt

I have a set of parameters that I need to edit, some of which are enums.

As of today, I use the raw value of the enum in a QSpinBox, which is not friendly at all. You have to remember the values by yourself and set the good one:

my parameter editor

For instance, E_Range could be presenting a combobox with these:

typedef enum {
    ERANGE_2_5  = 0, /*!< +/- 2.5 V */
    ERANGE_5    = 1, /*!< +/- 5 V */
    ERANGE_10   = 2, /*!< +/- 10 V */
    ERANGE_AUTO = 3  /*!< Auto range */
} TVoltageRange_e;

I didn't find anything about using an enum in a QComboBox. Is it possible?
If yes, what are the steps?

I mean, I guess I'll have to declare the enum through Qt so that it is "enumerable" with the Qt metaobject. But from there, I'm not sure.

like image 627
Gui13 Avatar asked Jun 06 '13 07:06

Gui13


People also ask

How do I add items to QComboBox?

A combobox can be populated using the insert functions, insertItem() and insertItems() for example. Items can be changed with setItemText(). An item can be removed with removeItem() and all items can be removed with clear().

What is a QComboBox?

A QComboBox provides a means of presenting a list of options to the user in a way that takes up the minimum amount of screen space. A combobox is a selection widget that displays the current item, and can pop up a list of selectable items. A combobox may be editable, allowing the user to modify each item in the list.

What is enum in Qt?

An enumerated type, or enum, is a data type consisting of a set of named values called elements, members, enumeral, or enumerators of the type. Enums are incredibly useful when portraying status, options, or modes that are exclusive within a grouping.


1 Answers

Of course you can always hardcode the values, but as soon as you modify that enum you have to rememeber to change the code that populates your combobox.

I mean, I guess I'll have to declare the enum through Qt so that it is "enumerable" with the Qt metaobject. But from there, I'm not sure.

Exactly, using introspection is a smart move. Mark the enum with Q_ENUMS and add the Q_OBJECT macro. Then:

  • Grab your class' metaobject via Class::staticMetaObject()
  • Get the QMetaEnum for your enum via QMetaObject::indexOfEnumerator() + QMetaObject::enumerator()
  • Get the number of keys via QMetaEnum::keyCount(), and iterate getting the key names and their corresponding values (QMetaEnum::key(), QMetaEnum::keyToValue()).

With this you'll be able to populate your combobox programmatically (the typical pattern is to add the enum key as the user-visible string and the corresponding value as its "item data", cf. QComboBox's documentation.)

like image 156
peppe Avatar answered Sep 26 '22 12:09

peppe