Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt: Convert scoped enum to string using a template function

Tags:

c++

qt

For logging purpose I want to convert my enums to human readable strings. Most of the time I'm using scoped enums, therefore I need a solution that also works for scoped enums. Qt provides the Q_ENUM macro to safe me a lot of work. For converting a enum to string I can write this:

QMetaEnum::fromType<Class::Enum>().valueToKey(int(enum))

The explicit cast to int is necessary to convert the scoped enum to int, as valueToKey must be called using an integral value. This works for scoped enums but I would like to use some sort of template function for converting. I found the following template solution in a different question:

template<typename QEnum>
QString enumToString (QEnum value)
{
  return QMetaEnum::fromType<QEnum>().valueToKey(int(value));
}

But this does not work for scoped enums. Is there any template solution that also works for plain AND scoped enums?

EXAMPLE:

class LoggingManager : public QObject
{
    Q_OBJECT
public:
    enum class Level
    {
        debug,
        info,
        warning,
        error,
        fatal
    };
    Q_ENUM(LoggingManager::Level)

enum Category
        {
            network,
            usb
        };
        Q_ENUM(Category)
    ...
}

QString level = enumToString(LoggingManager::Level::debug) // ""
QString level2 = QMetaEnum::fromType<LoggingManager::Level>().valueToKey(int(LoggingManager::Level::debug)) // "debug"
QString category = enumToString(LoggingManager::usb) // "usb"
like image 529
Liachtei Avatar asked Oct 17 '25 02:10

Liachtei


1 Answers

Okay, i figured it out.

The solution is to not use the scoped enum in the Q_ENUM macro.

Wrong:

Q_ENUM(Class::Enum)

Correct:

Q_ENUM(Enum)

For most use cases using the scoped or the non-scoped form is equivalent (When you are inside the class). I normally always use the scoped form even inside the class just be clear about what I want to say. But it seems that using the scoped enum directly in the macro breaks the functionality of the macro.

Perhaps somebody with a deeper knowledge of Qt can explain why this is the case. But I just remember that using the scoped form in the macro makes it broken.

like image 148
Liachtei Avatar answered Oct 18 '25 18:10

Liachtei