Get String representation of all QMetaType::Type or QVariant::Type
-
As both enums aren't Q_ENUMs creating a QMetaEnum::fromType<QMetaType::Type>() won't work. Is there any other automated way to get all Types as QStrings? Or do i have to make a Map myself?
-
Hi,
Are you thinking about the QMetaType::name function ?
-
Yes but an automated way to get ALL enum - string pairs in a container.
For Q_ENUMs you can utilize QMetaEnum
enum Colour { red = 1, green = 2, blue = 3 } Q_ENUM(Numbers) QMap<Colour, QString> colourNames; QMetaEnum metaEnum = QMetaEnum::fromType<Colour>(); for(int i = 0; i < metaEnum.keyCount(); i++) colourNames.insert(metaEnum.value(i), metaEnum.key(i));
But the QMetaType::Type Enum is not a Q_ENUM, so QMetaEnum can't be used here.
-
Why do you want that? What will you do with it?
QMetaType::Type is not a Q_ENUM but even it it was it wouldn't contain the user registered QMetaTypes.
If for an obscure reason you do want to get ~all QMetaType, you could use the fact that QMetaType use an integer type id and loop over it.Something like the following:
for (int typeId = 1, consecutiveUnregisteredTypes = 0; typeId <= std::numeric_limits<int>::max() && consecutiveUnregisteredTypes < 1000; ++typeId) { if (!QMetaType::isRegistered(typeId)) { ++consecutiveUnregisteredTypes; continue; } consecutiveUnregisteredTypes = 0; qDebug() << typeId << QMetaType(typeId).name(); };
-
I want to add any QVariant type to a QTableWidget Cell. For this im using a QLineEdit QString and a QComboBox to determine which QVariant type the QString should be converted into. To populate my QComboBox i need the variants name to id pairs.
I've just made a small map manually to add types that can be converted from QString per default. But wouldn't it be nice to list all types, even user types?Iterating over all possible numbers does work, but i dont think its efficient, because there are large gaps inbetween them. Qt 6 introduced types with IDs starting at 0x1000 or 0x2000.
I've digged a bit into how QT generates the enum. It uses a macro which one could use to populate a map by introducing a new macro.#define METATYPE_ID_STRING_PAIR(TypeName, Id, Name) \ {Id, #TypeName}, QMap<int, QString> map = { QT_FOR_EACH_STATIC_TYPE(METATYPE_ID_STRING_PAIR) };
The UserTypes are stored in a QList so for them one could just use a loop again.
for (int typeId = QMetaType::User;; typeId++) { if (!QMetaType::isRegistered(typeId)) break; qDebug() << typeId << QMetaType(typeId).name(); };
-
I InTheBeninging has marked this topic as solved on
-
For Qt's own enum values you could use a library like https://github.com/Neargye/magic_enum or https://github.com/willwray/enum_reflect to get the strings for the enum values.