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 中使用枚举
基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01