0

It is ok to do the following:

Component {
    id: editDialogComp
    Dialog {
        onClosed: destroy()
    }
}

But what if I have

SpecialDialog.qml:

Item {
    Dialog {
        anchors.fill: parent
        ...
        onClosed: destroy() // is it ok?
    }
}

And then create the component:

QQmlComponent component(engine, "SpecialDialog.qml");
auto* object = component.beginCreate(engine->rootContext());
component.completeCreate();
QQmlEngine::setObjectOwnership(object, QQmlEngine::JavaScriptOwnership);

In the code above, if comment the destroy() call, the new Dialog will be created every time one opens the form and all the dialogs will not be destroyed until app exit.

Vladimir Bershov
  • 2,701
  • 2
  • 21
  • 51
  • I'm not sure your approach is correct. Maybe take a look at something like a [Loader](https://doc.qt.io/qt-6/qml-qtquick-loader.html) to dynamically add/remove components. – JarMan Aug 04 '23 at 13:00
  • I don't think closing a QML Dialog means that it has been destroyed, and your approach seems to be good. – SMR Aug 05 '23 at 12:38
  • from the [Qt6 QML Book](https://www.qt.io/product/qt6/qml-book/ch15-dynamicqml-dynamic-objects) - _Dynamically created objects can also be dynamically destroyed. When doing this, there is a rule of thumb: never attempt to destroy an object that you have not created_. – folibis Aug 05 '23 at 17:51
  • @folibis seems that be correct, see `SelfDestroyingRect` example here: https://doc.qt.io/qt-6/qtqml-javascript-dynamicobjectcreation.html#deleting-objects-dynamically – Vladimir Bershov Aug 05 '23 at 18:06
  • @VladimirBershov I see that you're creating your component with JavaScriptOwnership. This means when the object has no references left on it, the JavaScript garbage collector *MAY* destroy the object and reclaim its memory. As to when that happens, it is up to the garbage collector. However, if you are explicitly calling destroy(), that means you don't trust the garbage collector and you trying to force it to be destroyed asap. For troubleshooting, you can confirm whether your objects will get cleaned up by issuing a test call to `gc()`, but, generally, you should trust it. – Stephen Quan Aug 06 '23 at 00:28

0 Answers0