[Interest] QMetaType create

Jérôme Godbout jerome at bodycad.com
Wed Oct 5 22:42:36 CEST 2016


Hi,
I was looking for a way to create object dynamicaly out of a classname. I
have the classname which I can convert properly to QMetaType.

If the constructor is Q_INVOKABLE I can use the QMetaObject to create a
newInstance() and this work properly into the example.

But when this doesn't work, I'm trying to use the QMetaType::create() but
totally failed, it does return a pointer, but the memory seem to be bad for
this returned pointer. The doc say that QMetaType::create()  "If copy is
null,  creates a default constructed instance". My class does have a
default constuctor but just not Q_INVOKABLE, is that the problem?

http://doc.qt.io/qt-5/qmetatype.html#create

Here's a small sample :

QObject *create_child_instance_by_class_name(const char * class_name)
{
const int type = QMetaType::type(class_name);  // MyQObjectDerivatedClass*
here and it does return the proper type, check with a instance of the class
and this is ok
if(type == QMetaType::UnknownType)
return nullptr;
const auto type_flags = QMetaType::typeFlags(type);
if(0 == (type_flags & QMetaType::PointerToQObject))
return nullptr;

QObject *instance = nullptr;
if(!instance)
{
// Try default constructor from meta object
const QMetaObject* meta_object = QMetaType::metaObjectForType(type);
if(meta_object)
instance = meta_object->newInstance();
}
if(!instance)
{
// If not working try the meta type create directly
void* meta_obj_instance = QMetaType::create(type);
                // this pointer is bad and uninitialized
instance = static_cast<QObject*>(meta_obj_instance);
}
return instance;
}

Any idea why??? the create does return a pointer, I follow the code a bit
the proper ctor is detected but never seem to be called ?!? and the data
are totaly wrong.

Note the class is a User type defined by us but does have a default
constructor without argument :
class MyClass : public QObject
{
public:
   MyClass(QObject* parent = nullptr) : QObject(parent) {}
   ...
}
QML_DECLARE_TYPE(MyClass);

regards,
Thanks
Jerome
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20161005/741457d5/attachment.html>


More information about the Interest mailing list