How to identify child class when overriding childEvent?
-
Suppose classes:
class Controller : public QObject{ Q_OBJECT public: Controller(QObject* parent = nullptr) : QObject(parent){}; void childEvent(QChildEvent* event) override { if(event->added()){ if(event->child()->inherits("Foo"){ m_foo = qobject_cast<Foo*>(event->child()); } } } Foo* m_foo{nullptr}; }; class Foo : public QObject{ Q_OBJECT public: Foo(QObject* parent = nullptr) : QObject(parent){} }; int main(int argc, char argv**){ QCoreApplication app(argc, argv); Controller controller; Foo foo{&controller}; if(nullptr != controller.m_foo){ QTextStream(stdout) << "foo is set"; } else{ QTextStream(stdout) << "foo not set"; } auto ret = app.exec(); app.quit(); return ret; }
In the code as written above, foo will not be set. I assume, because the constructor of Foo sets the QObject's parent to "parent" before the rest of the construction is finished.
So if you change Foo's constructor to:
Foo(QObject* parent = nullptr) : QObject() { setParent(parent); }
then the code will identify the class.Or if you change, in main, to:
Foo foo; foo.setParent(&controller);
this will also identify the class.Is there some better approach I'm overlooking? Is there something Qt can do to get the constructors better set up to have the metadata available earlier?