Running JavaScript at StartupIt is occasionally necessary to run some imperative code at application (or component instance) startup. While it is tempting to just include the startup script as global code in an external script file, this can have severe limitations as the QML environment may not have been fully established. For example, some objects might not have been created or some Property Bindings may not have been run. QML JavaScript Restrictions covers the exact limitations of global script code.
The QML Component element provides an attached onCompleted property that can be used to trigger the execution of script code at startup after the QML environment has been completely established. For example:
Rectangle {
function startupFunction() {
// ... startup code
}
Component.onCompleted: startupFunction();
}Any element in a QML file - including nested elements and nested QML component instances - can use this attached property. If there is more than one onCompleted() handler to execute at startup, they are run sequentially in an undefined order.
Likewise, the Component::onDestruction attached property is triggered on component destruction.