Qt:在 QComboBox 中使用枚举 [英] Qt: using enums with QComboBox

查看:38
本文介绍了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
  • 通过QMetaEnum::keyCount()获取key的个数,并迭代获取key的名字和对应的值(QMetaEnum::key(), QMetaEnum::keyToValue()).
  • 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()).

有了这个,您将能够以编程方式填充您的组合框(典型的模式是将枚举键添加为用户可见的字符串,并将相应的值添加为其项目数据",参见 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 中使用枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆