Search code examples
c++qtenumsstring-formattingqstring

How can I use my enum in QString.arg()?


My enum is declared as Q_ENUM macro so it print the enum field's name when using with qDebug() (as I'm using QT 5.5) instead of its value. I'd like to do the same with QString().arg() so I declared that same enum with Q_DECLARE_METATYPE() macro but it didn't work either and give the below error.

Code:

qDebug() << QString("s = %1").arg(myClass::myEnum::ok);

error:

error: no matching function for call to 'QString::arg(myClass::myEnum)'

How can I fix this?


Solution

  • Q_ENUM does not provide a direct conversion to some kind of string value, so you would have to use QMetaEnum:

    qDebug() << QStringLiteral("s = %1").arg(QMetaEnum::fromType<MyClass::Priority>().valueToKey(static_cast<int>(myClass::myEnum::ok));

    static_cast is of course necessary for enum class.