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
QMetaEnumfor 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 中使用枚举
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
