如果type在namespace中,则QMetaObject :: newInstance会失败

时间:2016-02-19 12:42:45

标签: c++ qt qt5 qmetaobject

我想创建一个继承从A派生的基类的类QObject的新实例。

如果A不在命名空间中,这可以正常工作,但是如果A在命名空间中,则此调用返回空指针:

QObject *o = metaObject->newInstance(arg1,arg2,arg3);

metaObject本身返回正确的类名(包括命名空间)

std::cout << "Class name from staticMetaObject: " << metaObject->className() << std::endl;

A的构造函数标有Q_INVOKABLE。如何将QMetaObject::newInstance用于命名空间?

1 个答案:

答案 0 :(得分:1)

这绝对适用于Qt 5.5.1。

也许您的基类缺少Q_OBJECT宏。

// https://github.com/KubaO/stackoverflown/tree/master/questions/ns-meta-35505644
#include <QtCore>

int A_a, B_a;

class A : public QObject {
   Q_OBJECT
public:
   Q_INVOKABLE A(int a, QObject * parent = 0) : QObject{parent} {
      A_a = a;
   }
};

namespace NS {
class B : public A {
   Q_OBJECT
public:
   Q_INVOKABLE B(int a, QObject * parent = 0) : A{a, parent} {
      B_a = a;
   }
};
}

int main() {
   Q_ASSERT(A_a == 0);
   Q_ASSERT(B_a == 0);
   QScopedPointer<QObject> a {A::staticMetaObject.newInstance(Q_ARG(int, 10))};
   Q_ASSERT(A_a == 10);
   QScopedPointer<QObject> b {NS::B::staticMetaObject.newInstance(Q_ARG(int, 20))};
   Q_ASSERT(A_a == 20);
   Q_ASSERT(B_a == 20);
   QScopedPointer<QObject> c {b->metaObject()->newInstance(Q_ARG(int, 30))};
   Q_ASSERT(A_a == 30);
   Q_ASSERT(B_a == 30);
}

#include "main.moc"