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

2019-07-07 17:10发布

问题:

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?

回答1:

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.



回答2:

You could use the following conversion helper:

template <typename T>
typename QtPrivate::QEnableIf<QtPrivate::IsQEnumHelper<T>::Value , QString>::Type
toString(T enumValue)
{
   auto mo = qt_getEnumMetaObject(enumValue);
   auto enumIdx = mo->indexOfEnumerator(qt_getEnumName(enumValue));
   return QLatin1String(mo->enumerator(enumIdx).valueToKey(enumValue));
}

Then it becomes a simple matter:

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