Originally Posted by
tchoninho
In Java, any object can be instantiated and be called even if unknown. In Qt, I can only do this when I know that this object
Originally Posted by
squidge
Does QMetaObject provide the functionality of creating and object?
If there is a class called MyClass that extends QObject, is it possible to instantiate it from a QString?
What I mean is, having a QString className("MyClass"); is it possible to instantiate an object of type MyClass?
If an object does not inherit from QObject, then via:
int type = qRegisterMetaType<AClass>();
and
Q_DECLARE_METATYPE(AClass);
int type = qRegisterMetaType<AClass>();
and
Q_DECLARE_METATYPE(AClass);
To copy to clipboard, switch view to plain text mode
Is possible to instantiate an object knowing its int type returned from qRegisterMetaType, but then is there a way to use introspection to query the object about its methods and parameters?
For example in Java is possible to do the following:
Class myclass = Class.forName("MyClass");
Method[] methods = myclass.getMethods();
for (int i = 0; i < methods.length; i++)
{
// methods can also be invoked
System.out.println(methods[i].getName());
}
Class myclass = Class.forName("MyClass");
Method[] methods = myclass.getMethods();
for (int i = 0; i < methods.length; i++)
{
// methods can also be invoked
System.out.println(methods[i].getName());
}
To copy to clipboard, switch view to plain text mode
Is it possible to do something similar using Qt?
Added after 45 minutes:
Ah found it, for anyone interested:
Having the following class:
{
Q_OBJECT
public:
Q_INVOKABLE MyClass
(QObject *parent
= 0);
public:
Q_INVOKABLE void myMethod();
};
class MyClass : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE MyClass(QObject *parent = 0);
public:
Q_INVOKABLE void myMethod();
};
To copy to clipboard, switch view to plain text mode
Then the following code will print the above class methods:
MyClass *obj = static_cast<MyClass*>(MyClass::staticMetaObject.newInstance());
for (int i = 0; i < obj->metaObject()->methodCount(); i++)
{
qDebug() << method.signature();
}
MyClass *obj = static_cast<MyClass*>(MyClass::staticMetaObject.newInstance());
for (int i = 0; i < obj->metaObject()->methodCount(); i++)
{
QMetaMethod method = obj->metaObject()->method(i);
qDebug() << method.signature();
}
To copy to clipboard, switch view to plain text mode
the above will print something like:
destroyed()
deleteLater()
_q_reregisterTimers(void*)
myMethod()
destroyed(QObject*)
destroyed()
deleteLater()
_q_reregisterTimers(void*)
myMethod()
To copy to clipboard, switch view to plain text mode
Bookmarks