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

查看:599
本文介绍了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()为您的枚举获取 QMetaEnum QMetaObject :: enumerator()

  • 通过 QMetaEnum :: keyCount()获取键数code>,并反复获取键名及其对应的值( 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天全站免登陆