Component.onCompleted
runs as soon as the interpreter has read the QML file and parsed it into objects. Your "page 2" object is created at this time, but it has visible: false
so you can't see it. That doesn't keep the onCompleted
code from running.
I know of three ways to get code to run only when the page gets pushed to the stack:
Create a custom function that calls pageStack.push()
and triggers whatever other code you want run.
Move the code from page 2's onCompleted
handler to the onVisibleChanged
handler. Note that this will be called both when the page is pushed a popped from the stack; check the value of visible
to tell which is happening.
Move the page 2 object into a separate file, say "page2.qml", and change the push call to pageStack.push(Qt.resolvedUrl("page2.qml"))
. This will create a new page 2 object each time it's pushed to the stack; this may or may not be what you desire.
Note that all three of these will call the code each time page 2 is pushed to the stack. If you only want it to be called the first time, you'll have to keep track of that yourself. For more information on how object creation interacts with the pageStack, check out this answer.