Qt World Summit: Register Today!

How to identify child class when overriding childEvent?

  • Suppose classes:

    class Controller : public QObject{
    Controller(QObject* parent = nullptr) : QObject(parent){};
    void childEvent(QChildEvent* event) override {
                m_foo = qobject_cast<Foo*>(event->child());
    Foo* m_foo{nullptr};
    class Foo : public QObject{
    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";
            QTextStream(stdout) << "foo not set";
        auto ret = app.exec();
        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?

Log in to reply