0

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.

Paul Knopf
  • 9,568
  • 23
  • 77
  • 142
  • If you realize that depends on the Component that creates the object in QML, not the QObject, that is, the Component creates an object and adds it to the scene, the QObject does not know at what moment it started to be added to the scene if when finished. So for me it is impossible – eyllanesc Dec 27 '18 at 17:59
  • Ok. I wonder if there is a trick I could do with attached properties. Maybe create an attached property for my object, when it is called, reach out to the QQmlComponent attached property and listen to it's signal? – Paul Knopf Dec 27 '18 at 21:23
  • FYI, this is what I'm trying to achieve. https://github.com/qmlnet/qmlnet/issues/101 – Paul Knopf Dec 27 '18 at 21:24
  • The question is that onCompleted can be notified to the QObject since for the component to complete its task the object had to be created, but the onDestroyed I think it is not possible because the QObject was already destroyed – eyllanesc Dec 27 '18 at 21:28

1 Answers1

2

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.

GrecKo
  • 6,615
  • 19
  • 23