要在Q_ENUM中索引的值

时间:2018-04-22 23:26:49

标签: c++ qt enums qt5

QMetaEnum包含将枚举索引转换为实际值的方法:

int value(int index) const

但是如何转换回索引,例如,如果我想在某些控件中使用枚举,我需要按索引排序?

int index(int value) const

1 个答案:

答案 0 :(得分:2)

使用以下功能:

int indexFromValue(const QMetaEnum & e, int value){
    for(int ix=0; ix< e.keyCount(); ix++){
        if(e.key(ix) == e.valueToKey(value))
            return ix;
    }
    return -1;
}

示例:

#include <QCoreApplication>
#include <QMetaEnum>
#include <QObject>

class Foo : public QObject
{
    Q_OBJECT
public:
    using QObject::QObject;
    enum class FooEnumType { TypeA=10, TypeB=21 };
    Q_ENUM(FooEnumType)
};

static int indexFromValue(const QMetaEnum & e, int value){
    for(int ix=0; ix< e.keyCount(); ix++){
        if(e.key(ix) == e.valueToKey(value))
            return ix;
    }
    return -1;
}
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    const QMetaObject &mo = Foo::staticMetaObject;
    int index = mo.indexOfEnumerator("FooEnumType");
    QMetaEnum metaEnum = mo.enumerator(index);
    Q_ASSERT(indexFromValue(metaEnum, 10) == 0);
    Q_ASSERT(indexFromValue(metaEnum, 21) == 1);
    Q_ASSERT(indexFromValue(metaEnum, 100) == -1);
    return 0;
}

#include "main.moc"