View Full Version : Reflection on Qt
tchoninho
29th May 2011, 20:59
Hi everybody, I would use Reflection on Qt, but I do not know how I can do that. 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. Has anyone used Reflection in Qt?
My Object:
class Obj : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE Obj(QObject *parent = 0);
Q_INVOKABLE virtual ~Obj();
Q_INVOKABLE virtual QVariant execute (QList<QVariant> &);
Q_INVOKABLE uint getKey();
};
squidge
29th May 2011, 23:50
QMetaObject provides this functionality, you can use it to browse properties and methods of Qt Objects.
http://doc.qt.nokia.com/latest/qmetaobject.html
scieck
13th December 2011, 12:51
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
QMetaObject provides this functionality, you can use it to browse properties and methods of Qt Objects.
http://doc.qt.nokia.com/latest/qmetaobject.html
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);
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());
}
Is it possible to do something similar using Qt?
Added after 45 minutes:
Ah found it, for anyone interested:
Having the following class:
class MyClass : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE MyClass(QObject *parent = 0);
public:
Q_INVOKABLE void myMethod();
};
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++)
{
QMetaMethod method = obj->metaObject()->method(i);
qDebug() << method.signature();
}
the above will print something like:
destroyed(QObject*)
destroyed()
deleteLater()
_q_reregisterTimers(void*)
myMethod()
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.