Last active
September 19, 2022 18:18
-
-
Save MoeQatoum/4107191ef11b804f7bf7c12d51fb8321 to your computer and use it in GitHub Desktop.
C++ Qt how convert Q_ENUM to QString, std::string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"CAT" | |
CPP | |
MyNameSpace::Animal::MONKEY | |
MyNameSpace::Animal(-1) // MyNameSpace::Animal::C is not valid | |
MyNameSpace::C | |
MyNameSpace::Animal::CAT | |
MyNameSpace::PYTHON | |
"CAT" | |
"CPP" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// credits to @Meefte answer. https://stackoverflow.com/a/34282031/14745345 | |
// https://doc.qt.io/qt-5/qmetaenum.html#keyToValue | |
// https://doc.qt.io/qt-5/qobject.html#Q_ENUM | |
// https://doc.qt.io/qt-5/qobject.html#Q_ENUM_NS | |
#include <QtCore> | |
#include <iostream> | |
namespace MyNameSpace | |
{ | |
Q_NAMESPACE | |
enum class Animal | |
{ | |
CAT = 10, | |
DOG, | |
MONKEY | |
}; | |
Q_ENUM_NS(Animal); | |
enum Language | |
{ | |
CPP, | |
C, | |
PYTHON | |
}; | |
Q_ENUM_NS(Language); | |
} | |
template <typename QEnum> | |
QString QtEnumToQString(const QEnum value) | |
{ | |
return QString(QMetaEnum::fromType<QEnum>().valueToKey((int)value)); // or c++23 version .valueToKey(std::to_underlying(value)) | |
} | |
template <typename QEnum> | |
std::string QtEnumToString(const QEnum value) | |
{ | |
return std::string(QMetaEnum::fromType<QEnum>().valueToKey(value)); | |
} | |
template <typename QEnum> | |
QEnum QStringToQtEnum(const QString value) | |
{ | |
return (QEnum)QMetaEnum::fromType<QEnum>().keysToValue(value.toUtf8().data()); | |
} | |
template <typename QEnum> | |
QEnum charToQtEnum(const char *value) | |
{ | |
return (QEnum)QMetaEnum::fromType<QEnum>().keysToValue(value); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
qDebug() << QtEnumToQString<MyNameSpace::Animal>(MyNameSpace::Animal::CAT); | |
qDebug() << QtEnumToString<MyNameSpace::Language>(MyNameSpace::CPP).c_str() << "\n"; | |
qDebug() << QStringToQtEnum<MyNameSpace::Animal>("MONKEY"); | |
qDebug() << QStringToQtEnum<MyNameSpace::Animal>("C"); | |
qDebug() << QStringToQtEnum<MyNameSpace::Language>("C") << "\n"; | |
qDebug() << charToQtEnum<MyNameSpace::Animal>("CAT"); | |
qDebug() << charToQtEnum<MyNameSpace::Language>("PYTHON") << "\n"; | |
qDebug() << QtEnumToQString<MyNameSpace::Animal>(QStringToQtEnum<MyNameSpace::Animal>("CAT")); | |
qDebug() << QtEnumToQString<MyNameSpace::Language>(QStringToQtEnum<MyNameSpace::Language>("CPP")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment