0

我想创建一个新的类实例,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命名空间?

4

1 回答 1

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"
于 2016-02-19T15:25:53.533 回答