まず第一に、パラメーターをメソッドに渡すには、単純な C++ を超えたある種のリフレクション フレームワークが必要です。Qt では、明らかな選択は Qt メタ オブジェクト システムでQMetaObject
あり、その場合は のクラスを派生させる必要がありますQObject
。その後、次の 2 つのことを行う必要があります。
1. コンストラクターを呼び出し可能にする
シグナルとスロットはデフォルトで呼び出し可能ですが、メタ オブジェクト システムを介して呼び出したい他のメソッドは、そのように明示的にマークする必要があります。例myqobject.h :
#ifndef MYQOBJECT_H
#define MYQOBJECT_H
#include <QObject>
class MyQObject : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE MyQObject(QObject *parent = 0); // tested with empty constructor in .cpp
};
#endif // MYQOBJECT_H
2. クラス名文字列からQMetaObject
QMetaType
doc は次のように述べています。これは、コピー コンストラクターを持つことができないため、QObject を除外します。名前からメタ オブジェクトへの独自のマッピングを作成する必要があります。このmain.cppに示されている例:
#include <QCoreApplication>
#include <QtCore>
#include "myqobject.h"
// a global map for mapping strings to QMetaObjects,
// you need header file like this if you want to access it from other .cpp files:
//
// #include <QHash>
// #include <QString>
// class QMetaObject; // forward declaration, enough when only pointer is needed
// extern QHash<QString, const QMetaObject*> metaObjs;
//
QHash<QString, const QMetaObject*> metaObjs;
// optional: create a macro to avoid typing class name twice,
// #c surrounds macro argument with double quotes converting it to string
#define METAOBJS_INSERT(c) (metaObjs.insert(#c, &c::staticMetaObject))
int main()
{
METAOBJS_INSERT(MyQObject);
const QMetaObject *meta = metaObjs["MyQObject"];
qDebug() << "Class name from staticMetaObject: " << meta->className();
QObject *o = meta->newInstance(); // add constructor arguments as needed
MyQObject *mo = qobject_cast<MyQObject*>(o);
if (mo) qDebug() << "Class name from object instance: " << mo->metaObject()->className();
else qDebug() << "Instance creation failed or created wrong class!";
return 0;
}
を使用したくない場合QObject
は、独自の同様の(おそらく軽量で、別のコンパイラステップがない)メカニズムを考え出す必要があります。