c++ - 将私有(private)子类添加到 Q_DECLARE_METATYPE

标签 c++ qt qvariant

如何将 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 是私有(private)的。

最佳答案

要在 MySubClass 中使用 QMetaType,它需要可公开访问。

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

如果您希望能够通过信号/槽发送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.

如果您只想将 MySubClass 实例存储在 QVariant 中,您可以编写自己的转换方法

QVariant toVariant() const

(static) MySubClass fromVariant(QVariant const &v)

为了确保类型安全,您可以创建一些公共(public)虚拟类型并将其注册到 QMetaType 中,这样您就可以获得一个唯一的 ID,但基本上您会转换您的 MySubClass > 到 QVariantMap 并返回,前提是所有包含的数据都可存储在 QVariant 中。

关于c++ - 将私有(private)子类添加到 Q_DECLARE_METATYPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56923689/

相关文章:

c++ - 如何在其他 linux 平台上部署带有所有 dll 文件的 Qt 应用程序?

c++ - 在 Qt 中的 C++ 中添加 C 函数时出现问题

c++ - QML "QtQuick.PrivateWidgets"未找到插件 "widgetsplugin"

c++ - 尝试从文本文件读取到对象数组

c++ - C/C++读取UART端口并显示结果

c++ - 简单的 C++ vector 程序未编译

c++ - 加载特定网站时 QtWebKit 2.2 段错误

qvariant - 如何访问作为 QVariantMap 值的数组?

list - QVariantList.append() 合并列表而不是嵌套