Reputation: 82
I want to create a new instance of class A
that inherits a base class derived from QObject
.
In case A
isn't in a namespace this works fine, but in case A
is in a namespace this call returns a null pointer:
QObject *o = metaObject->newInstance(arg1,arg2,arg3);
The metaObject
itself returns the correct class name (including the namespace)
std::cout << "Class name from staticMetaObject: " << metaObject->className() << std::endl;
The constructor of A
is marked with Q_INVOKABLE
. How can I use QMetaObject::newInstance
with namespaces?
Upvotes: 0
Views: 1251
Reputation: 98495
It definitely works for me under Qt 5.5.1.
Perhaps your base class is missing the Q_OBJECT
macro.
// 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"
Upvotes: 1