Tuesday, May 25, 2010

Enum value to String in Qt

Update:

it looks like that Qt framework made some changes that made staticQtMetaObject as protected.

Now to get staticQtMetaObject you need to use following code.
class StaticQtMetaObject : public QObject
{
public:
    static inline const QMetaObject& get() {return staticQtMetaObject;}
};
then use it like following
QString KeyboardOptionWidget::getKeyString( int aKeyCode )
{
    int index = StaticQtMetaObject::get().indexOfEnumerator("Key");
    QMetaEnum metaEnum = StaticQtMetaObject::get().enumerator( index);
    QString keyString = metaEnum.valueToKey( aKeyCode );
    return keyString.replace("Key_","");
    return QString();
}
--------------
Some time we might need to convert Enum value to string for various reason like logging or debugging. I also needed similar thing for one of my project.

I found one interesting code that uses Qt's meta-object system to convert Enum to String. I have created one similar function that convert key board code to string.

QString KeyboardOptionWidget::getKeyString( int aKeyCode )
{
    int index = QApplication::staticQtMetaObject.indexOfEnumerator("Key");
    QMetaEnum metaEnum = QApplication::staticQtMetaObject.enumerator( index);
 
    QString keyString = metaEnum.valueToKey( aKeyCode );
    return keyString.replace("Key_","");
} 

Hope this helps.

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete