将私人子 class 添加到 Q_DECLARE_METATYPE

Add private sub class to Q_DECLARE_METATYPE

如何将 MySubClass 添加到 Q_DECLARE_METATYPE。

这是示例代码,请忽略代码业务。

#include <QMetaType>
#include <QVariant>
#include <QDebug>

namespace MyNS {
    class MyClass : public QObject {
    public:
        MyClass() : value(0) { }
        MyClass(int value) : value(value) { }
        MyClass(const MyClass &other) { value = other.value; }
        ~MyClass() { }
        int getValue() const {
            MySubClass msc(value);
            QVariant v = QVariant::fromValue(msc);
            int tempV = v.value<MySubClass>().getSubValue();
            return tempV;
        }
    private:
        class MySubClass
        {
        public:
            MySubClass() : subValue(0) {}
            MySubClass(int v) : subValue(v)
            {

            }
            int getSubValue()
            {
                return subValue;
            }
        private:
            int subValue;
        };
//        Q_DECLARE_METATYPE(MySubClass);  error : 'QMetaTypeId<MyNS::MyClass::MySubClass>': cannot specialize template in current scope
        int value;
    };

//    Q_DECLARE_METATYPE(MySubClass);  error : 'MySubClass': undeclared identifier
}

Q_DECLARE_METATYPE(MyNS::MyClass);

int main(int argc, char *argv[])
{
    MyNS::MyClass m(15);
    QVariant v = QVariant::fromValue(m);
    qDebug() << v.canConvert<MyNS::MyClass>();
    qDebug() << v.value<MyNS::MyClass>().getValue();
}

考虑 MyClass 在没有子类的情况下工作得很好,但我的子类问题。我想在我的代码中使用 MySubClass 和 QVariant,但是 MySubClass 是私有的。

要将 QMetaType 用于您的 MySubClass,它需要 public 盟友可以访问。

想想为什么要插入MySubClass到Qt的元类型系统?

如果你希望能够通过signal/slot发送MySubClass,或者(反)序列化/流式传输它,这将使MySubClass 具有 public 兴趣。 The docs tell you so:

Before we begin, we need to ensure that the custom type we are creating meets all the requirements imposed by QMetaType. In other words, it must provide:

a public default constructor,
a public copy constructor, and
a public destructor.

如果你只想在QVariant中存储MySubClass个实例,你可以自己写转换方法

QVariant toVariant() const

(static) MySubClass fromVariant(QVariant const &v)

要成为 type-safe,您可以创建一些 public 虚拟类型并将其注册到 QMetaType,这样您将获得一个唯一的 ID,但基本上您会转换您的 MySubClassQVariantMap 并返回,前提是所有包含的数据都可存储在 QVariant.