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

纵然是瞬间 提交于 2019-12-12 18:27:28

问题


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));


来源:https://stackoverflow.com/questions/32639593/how-can-i-use-my-enum-in-qstring-arg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!