在 QML 中,我有一個 Component ( id: sharedComponent) 的實體,我想在兩個 QML 中使用它,這些 QMLPage在StackView. 但是,sharedComponent只有在page1中處于活動狀態時才可見StackView,即,只要page2按下,藍色矩形就會消失StackView。
如何在 QML 的多個頁面中共享/使用/查看組件的實體?
我的頁面.qml
Page {
default property alias mainContent: mainContent.data
Item {
id: mainContent
anchors.fill: parent
}
}
主檔案
ApplicationWindow {
id: window
width: 640
height: 480
visible: true
Rectangle {
id: sharedComponent
anchors.fill: parent
color: "blue"
// in my actual software, this shared component would contain a Scene3D here
}
MyPage {
id: page1
mainContent: sharedComponent
}
MyPage {
id: page2
mainContent: sharedComponent
}
StackView {
id: stackView
initialItem: page1
anchors.fill: parent
}
Button {
text: "Switch Page"
anchors.centerIn: parent
onClicked: {
if(stackView.depth>1) {
stackView.pop()
} else {
stackView.push(page2)
}
}
}
}
uj5u.com熱心網友回復:
為了共享一個物件,共享物件需要重新父級。當不同的 MyPage 實體變得可見時,它需要成為 sharedObject 的父級。因此,開始將可見設定為 false 的頁面。
我的頁面.qml:
Page {
property Item mainContent
Item {
id: container
anchors.fill: parent
}
onVisibleChanged: {
if (visible) {
// Take ownership of the shared object
mainContent.parent = container
}
}
}
主.qml:
ApplicationWindow {
...
Rectangle {
id: sharedComponent
anchors.fill: parent
color: "blue"
}
MyPage {
id: page1
mainContent: sharedComponent
// When visible becomes true, page1 becomes the parent
visible: false
}
MyPage {
id: page2
mainContent: sharedComponent
// When visible becomes true, page2 becomes the parent
visible: false
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/395705.html
