0

I've started learning QML with Qt6 lately and am trying to apply "best practices" right from the start. When it comes to integrating C++ it seems that a family of macros (QML_ELEMENT and friends) is going to replace the old style *register functions. A best practices talk on the Qt youtube channel calls this "declarative registration". I've tried that in a small example using CMake and it practically worked out of the box.

Now to my knowledge C++ classes exported and instantiated within a QML module have "QML engine" ownership. Lets suppose I'd rather have C++ take ownership of my class and QML merely use it, how would I inform the QML engine about my instance? Do I need to use setContextProperty for that?

I've also wondered what benefits and drawbacks I'd get from letting either C++ or QML handle ownership? There seems to be hardly any information on those topics. I've even browsed a couple of Qt books and not a single one would elaborate on that...

Vinci
  • 1,382
  • 10
  • 12
  • 2
    You can explicitly call `QQmlEngine::setObjectOwnership(myObject, QQmlEngine::CppOwnership)`, if you can get a pointer to your object. But it would be easier to use setContextProperty on an object already created in C++. – JarMan Jan 12 '22 at 18:29
  • I probably should have watched the best practices talk a little longer. Somewhere around minute 8 they mention that there is a new alternative to [setContextProperty](https://doc.qt.io/qt-6/qqmlcontext.html#setContextProperty) called [setInitialProperties](https://doc.qt.io/qt-6/qqmlapplicationengine.html#setInitialProperties). – Vinci Jan 13 '22 at 07:19

0 Answers0