简体   繁体   中英

StackView - Popped screen gets destroyed after previous screen is made visible

StackView has screen 1 as initial item. Screen 2 is pushed. Screen 2 is now popped.
Screen 2 gets destroyed after screen 1 is made visible.
Is this expected behavior? Why does it work this way?
I expected the popped screen to get destroyed before the previous screen is made visible.

Code to demonstrate the same:

StackView {
    id: stack
    initialItem: mainView1
    anchors.fill: parent
}
Component {
    id: mainView1
    Text {
        text: "1"
        onVisibleChanged: console.log(text, visible)
        Component.onCompleted: console.log(text, "completed")
        Component.onDestruction: console.log(text, "destroyed")
    }
}
Component {
    id: mainView2
    Text {
        text: "2"
        onVisibleChanged: console.log(text, visible)
        Component.onCompleted: console.log(text, "completed")
        Component.onDestruction: console.log(text, "destroyed")
    }
}

Console output:

qml: 1 completed
qml: Push
qml: 2 completed
qml: 1 false
qml: Pop
qml: 1 true
qml: 2 false
qml: 2 destroyed

Motivation behind the question:
I need to control a C++ timer from QML. Timer needs to be started when widget is created/visible and stopped when widget is destroyed/hidden.
The above depicted behavior of StackView prevents me from achieving it.
When I pop screen 2, screen 1 is first made visible, so my timer starts. Screen 2 then gets destroyed, as a result, my timer is stopped.

The reason why this occurs is due to StackView animation. Both views must exist during the default push and pop animations as they both appear on screen at the same time.

You likely can solve your problem using the StackView attached signals:

https://doc.qt.io/qt-5/qml-qtquick-controls2-stackview.html#attached-signals

These are signals that fire on your views regarding their individual status as the StackView pushes and pops.

If you haven't used attached signals before, here's some documentation on how they work:

https://doc.qt.io/qt-5/qtqml-syntax-objectattributes.html#attached-properties-and-attached-signal-handlers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM