在q_enum中索引的价值



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

int value(int index) const

但是如何将索引转换回索引

int index(int value) const

使用以下功能:

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"

相关内容

  • 没有找到相关文章