具有自定义类指针的QVariant不会返回相同的地址 [英] QVariant with custom class pointer does not return same address

查看:172
本文介绍了具有自定义类指针的QVariant不会返回相同的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用QQmlContext::setContextProperty()在qml中分配一个指向自定义类的指针.另一个qml对象具有相同类型的Q_PROPERTY以便再次检索它.

I need to assign a pointer to a custom class in qml using QQmlContext::setContextProperty(). Another qml object has Q_PROPERTY of the same type to retrieve it again.

一个简单的测试告诉我,该转换无法像我所想的那样工作.

A simple test showed me that the conversion does not work like i thought.

#include <QCoreApplication>
#include <QDebug>
#include <QMetaType>

class TestClass
{
public: TestClass() { qDebug() << "TestClass()::TestClass()"; }
};

Q_DECLARE_METATYPE(TestClass*)

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    qDebug() << "metaTypeId =" << qMetaTypeId<TestClass*>();

    auto testObject = new TestClass;
    QVariant variant(qMetaTypeId<TestClass*>(), testObject);
    auto test = variant.value<TestClass*>();

    qDebug() << testObject << variant << test;

    return 0;
}

这个小小的测试应用程序给了我这样的输出:

This tiny test application gives me an output like this:

metaTypeId = 1024
TestClass::TestClass()
0x1b801e0 QVariant(TestClass*, ) 0x0

我真的很想在将其转换为QVariant之后再次获得相同的指针.稍后,我将其分配给qml上下文,然后对话必须正确进行.

I would really like to get the same pointer out again after converting it down to a QVariant. Later I will assign it to a qml context and then the conversation must work correctly.

推荐答案

这适用于我使用Qt 5.9的情况:

This works for me using Qt 5.9:

#include <QVariant>
#include <QDebug>

class CustomClass
{
public:
    CustomClass()
    {
    }
};    
Q_DECLARE_METATYPE(CustomClass*)

class OtherClass
{
public:
    OtherClass()
    {
    }
};
Q_DECLARE_METATYPE(OtherClass*)

int main()
{
    CustomClass *c = new CustomClass;
    OtherClass *o = new OtherClass;
    QVariant v;
    v.setValue(c);
    QVariant v2;
    v2.setValue(o);

    qDebug() << v.userType() << qMetaTypeId<CustomClass*>() << v2.userType() << qMetaTypeId<OtherClass*>();
    qDebug() << v.value<CustomClass*>() << c << v2.value<OtherClass*>() << o;

    return 0;
}

我得到的输出是:

1024 1024 1025 1025
0x81fca50 0x81fca50 0x81fca60 0x81fca60

这篇关于具有自定义类指针的QVariant不会返回相同的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆