2

在一个项目中是自定义记录器,我想将其扩展为像 qDebug() 那样写入枚举值。有一些简单的方法吗?

这是我认为可能有用的东西(但它没有):

template <typename T>
typename QtPrivate::QEnableIf<QtPrivate::IsQEnumHelper<T>::Value, std::ostream>::Type
operator<<(std::ostream& os, T enumValue)
{
    const QMetaObject* mo = qt_getEnumMetaObject(enumValue);
    int enumIdx = mo->indexOfEnumerator(qt_getEnumName(enumValue));
    return os << mo->enumerator(enumIdx).valueToKey(enumValue);
}

class MyObjet : public QObject
{
    Q_OBJECT
public:
    enum class Action { Open, Save, New, Copy, Cut, Paste, Undo, Redo, Delete };
    Q_ENUM(Action)
    explicit MyObjet(QObject* parent);
    void myFunction(Action a)
    {
        std::count << "Action is:" << a << std::endl;
    }
};
4

1 回答 1

2

这是插入运算符重载,我把它放在一个名为qtenum2ostream.h的头文件中:

#ifndef QTENUM2OSTREAM_H
#define QTENUM2OSTREAM_H

#include <QMetaEnum>

template<typename T>
typename std::enable_if<QtPrivate::IsQEnumHelper<T>::Value, std::ostream  &>::type
operator<<(std::ostream & o, const T & t)
{
    const QMetaObject* metaobject = qt_getEnumMetaObject(t);
    int enumindex = metaobject->indexOfEnumerator(qt_getEnumName(t));
    o << metaobject->enumerator(enumindex).valueToKey(static_cast<int>(t));
    return o;
}

#endif // QTENUM2OSTREAM_H

您现在可以在示例类中使用它:

#include "qtenum2ostream.h"
#include <iostream>

#include <QObject>

class MyObject : public QObject {
    Q_OBJECT
public:
    enum class Action { Open, Save, New, Copy, Cut, Paste, Undo, Redo, Delete };
    Q_ENUM(Action)
    void myFunction(Action a)
    {
        std::cout << "Action is:" << a << std::endl;
    }
};
于 2017-12-28T11:26:00.453 回答