Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. How to identify child class when overriding childEvent?
Forum Update on Monday, May 27th 2025

How to identify child class when overriding childEvent?

Scheduled Pinned Locked Moved General and Desktop
childeventqobject
1 Posts 1 Posters 1.0k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    shavera
    wrote on 24 Jul 2015, 15:53 last edited by shavera
    #1

    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?

    1 Reply Last reply
    0

    1/1

    24 Jul 2015, 15:53

    • Login

    • Login or register to search.
    1 out of 1
    • First post
      1/1
      Last post
    0
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Get Qt Extensions
    • Unsolved