Other solution is ... to create attached properties
namespace MessageTypes {
Q_NAMESPACE
QML_ELEMENT
enum class Type {
None,
SessionOpened,
ConfigurationExternal,
ConfigurationGet,
};
Q_ENUM_NS(Type)
inline static const QMap<Type, QString>& typeToString() {
static const QMap<Type, QString> map = {
{Type::None, "None"},
{Type::SessionOpened, "SessionOpened"},
{Type::ConfigurationExternal, "configuration/external"},
{Type::ConfigurationGet, "configuration/get"},
};
return map;
}
inline static const QMap<QString, Type>& stringToType() {
static QMap<QString, Type> reverseMap = []() {
QMap<QString, Type> map;
for (auto it = MessageTypes::typeToString().cbegin();
it != MessageTypes::typeToString().cend(); ++it) {
map.insert(it.value(), it.key());
}
return map;
}();
return reverseMap;
}
}
// Attached object type - contains the utility methods
class MessageTypesAttached : public QObject
{
Q_OBJECT
QML_ANONYMOUS // Not directly instantiable
public:
explicit MessageTypesAttached(QObject *parent = nullptr)
: QObject(parent)
{}
// Helper functions
Q_INVOKABLE inline static QString toString(MessageTypes::Type type) {
return MessageTypes::typeToString().value(type, QString());
}
Q_INVOKABLE inline static MessageTypes::Type fromString(const QString& str, MessageTypes::Type defaultValue = MessageTypes::Type::None) {
return MessageTypes::stringToType().value(str, defaultValue);
}
Q_INVOKABLE inline static QStringList getAllTypesName() {
return MessageTypes::typeToString().values();
}
}
// Attaching type - provides access to the attached object
class MessageTypesUtils : public QObject
{
Q_OBJECT
QML_ELEMENT
QML_UNCREATABLE("MessageTypesUtils is only for attached properties")
QML_ATTACHED(MessageTypesAttached)
public:
explicit MessageTypesUtils(QObject *parent = nullptr)
: QObject(parent)
{}
// Required static method for attached properties
static MessageTypesAttached *qmlAttachedProperties(QObject *object)
{
return new MessageTypesAttached(object);
}
};