Qt: using enums with QComboBox(Qt:在 QComboBox 中使用枚举)
问题描述
我有一组需要编辑的参数,其中一些是枚举.
I have a set of parameters that I need to edit, some of which are enums.
截至今天,我在 QSpinBox 中使用枚举的原始值,这一点都不友好.你必须自己记住这些值并设置好的:
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:
例如,E_Range 可能会显示一个包含以下内容的组合框:
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;
我没有找到有关在 QComboBox 中使用枚举的任何信息.有可能吗?
如果是,步骤是什么?
I didn't find anything about using an enum in a QComboBox. Is it possible?
If yes, what are the steps?
我的意思是,我想我必须通过 Qt 声明枚举,以便它与 Qt 元对象可枚举".但从那里开始,我不确定.
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.
推荐答案
当然,您始终可以对值进行硬编码,但是一旦修改了该枚举,您就必须记住更改填充组合框的代码.
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.
我的意思是,我想我必须通过 Qt 声明枚举,以便它与 Qt 元对象可枚举".但从那里开始,我不确定.
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.
确实,使用自省是明智之举.用 Q_ENUMS
标记枚举并添加 Q_OBJECT
宏.然后:
Exactly, using introspection is a smart move. Mark the enum with Q_ENUMS
and add the Q_OBJECT
macro. Then:
- 通过
Class::staticMetaObject()
获取你的类的元对象 - 通过
QMetaObject::indexOfEnumerator()
+QMetaObject::enumerator()
获取枚举的 - 通过
QMetaEnum::keyCount()
获取key的个数,并迭代获取key的名字和对应的值(QMetaEnum::key()
,QMetaEnum::keyToValue()
).
QMetaEnum
- Grab your class' metaobject via
Class::staticMetaObject()
- Get the
QMetaEnum
for your enum viaQMetaObject::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()
).
有了这个,您将能够以编程方式填充您的组合框(典型的模式是将枚举键添加为用户可见的字符串,并将相应的值添加为其项目数据",参见 QComboBox代码>的文档.)
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.)
这篇关于Qt:在 QComboBox 中使用枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Qt:在 QComboBox 中使用枚举


- 从python回调到c++的选项 2022-11-16
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
- C++ 协变模板 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07