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:
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.
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().
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.
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.
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:
Class::staticMetaObject()
QMetaEnum
for your enum via QMetaObject::indexOfEnumerator()
+ QMetaObject::enumerator()
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With