Search code examples
c++qtqmlqt-signals

Listening to attached Component.onCompleted and Component.onDestroyed signals from C++ Q_OBJECT


I have a C++ Q_OBJECT (registered with qmlRegisterType) that I'd like to perform some actions on Component.onCompleted and Component.onDestroyed.

Is there a way to subscribe to those handlers without writing any QML?

It looks like I could use QQmlEnginePrivate::registerFinalizeCallback, but it would depend on private headers.


Solution

  • This can be done with QQmlParserStatus

    To use QQmlParserStatus, you must inherit both a QObject-derived class and QQmlParserStatus, and use the Q_INTERFACES() macro.

    class MyObject : public QObject, public QQmlParserStatus
    {
        Q_OBJECT
        Q_INTERFACES(QQmlParserStatus)
    
    public:
        MyObject(QObject *parent = 0);
        ...
        void classBegin() override;
        void componentComplete() override;
    }
    

    classBegin can be useful to mark that an instance has been created from QML. It can make sense to do some initialization in componentComplete if it has been created from QML but do nothing if it has been created from c++.

    As for the onDestroyed, you can connect something to the QObject::destroyed signal. Note that when destroyed is emitted your object is just a QObject, all the subclasses' destructors have already been called.