我想创建一个继承从QObject
派生的基类的类A
的新实例。
如果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
与命名空间一起使用?
在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"