我们知道在许多的项目中,当切换到一个页面时我们需要对一些资源进行监控.每当发送事件改变时,我们需要进行更新我们的页面.当然每当我们离开我们的页面时,我们就不想做这样的动作.我们可以取消或释放我们所需要的资源以节省资源.当我们需要这么做的时候,我们希望得到页面切换时的事件这样我们可以在合适的时机做出合适的动作.Qt中的Component.incubateObject()为我们提供了这样一个监控的机制.
下面我们用一个简单的例程来说明这个问题:
Main.qml
import QtQuick 2.4
import Ubuntu.Components 1.3
MainView {
id: mainview
// objectName for functional testing purposes (autopilot-qt5)
objectName: "mainView"
// Note! applicationName needs to match the "name" field of the click manifest
applicationName: "pagedestroyevent.liu-xiao-guo"
width: units.gu(60)
height: units.gu(85)
property int index: 0
Component {
id: page2Component
Page {
id: page
header: PageHeader {
id: header
title: "Second Page"
}
Column {
anchors.centerIn: parent
spacing: units.gu(5)
Text {
text: "Page: " + index
}
Button {
text: "Close me"
onClicked: pageStack.removePages(pageStack.primaryPage);
}
}
}
}
AdaptivePageLayout {
id: pageLayout
anchors.fill: parent
primaryPage: Page {
header: PageHeader {
title: "Primary Page"
flickable: listView
}
ListView {
id: listView
anchors.fill: parent
model: 10
delegate: ListItem {
Label { text: modelData }
onClicked: {
mainview.index = index
var incubator = pageLayout.addPageToNextColumn(pageLayout.primaryPage, page2Component);
if (incubator && incubator.status === Component.Loading) {
incubator.onStatusChanged = function(status) {
if (status === Component.Ready) {
// connect page's destruction to decrement model
incubator.object.Component.destruction.connect(function() {
console.log("it is destructed! " + index)
});
}
}
}
}
}
}
}
}
}
在上面的例程中我们运用 AdaptivePageLayout来实现我们的布局.运行我们的应用:
每当我们打开ListView中的一项的时候,我们通过:
var incubator = pageLayout.addPageToNextColumn(pageLayout.primaryPage, page2Component);
把我们的新的一页加入到pageStack中,同时,我们可以利用incubator对刚刚加入的页面进行lifecycle的管理:
if (incubator && incubator.status === Component.Loading) {
incubator.onStatusChanged = function(status) {
if (status === Component.Ready) {
// connect page's destruction to decrement model
incubator.object.Component.destruction.connect(function() {
console.log("it is destructed! " + index)
});
}
}
}
每当一个页面被销毁时,我们将收到一个输出:
qml: it is destructed! 0
qml: it is destructed! 5
qml: it is destructed! 5
qml: it is destructed! 3
qml: it is destructed! 0
qml: it is destructed! 4
qml: it is destructed! 7