@TheBootroo提供的答案在這裏:link如何在QML中訪問動態/隨機加載的Repeater項目?
提供了一種在QML文件/屏幕/視圖之間加載和更改的方法。但是,像這樣做時,如何使用信號和插槽?
可以使用Repeater :: itemAt(index)方法訪問由repeater創建的項目,但由於我不知道按什麼順序加載項目,我不知道索引screen2,screen3, screen4等是在。
有什麼辦法可以解決這個問題嗎?還是必須在啓動時實例化內存中的所有屏幕?
我下面的代碼:
main.qml:
//List of screens
property variant screenList: [
"main",
"screen2",
"screen3",
...
]
//Set this to change screen
property string currentScreen: "main"
Repeater {
id: screens
model: screenList
delegate: Loader {
active: false;
asynchronous: true
anchors.fill: parent
source: "%1.qml".arg(modelData)
visible: (currentScreen === modelData)
onVisibleChanged: {
loadIfNotLoaded()
}
Component.onCompleted: {
loadIfNotLoaded()
}
function loadIfNotLoaded() {
//To load start screen
if(visible && !active) {
active = true;
}
}
}
}
Connections {
target: screens.itemAt(indexHere)
//screen is here the string passed with the signal from screen2.
onChangeScreen: currentScreen = screen
}
Button {
id: button1
text: "Go To Screen 2"
onClicked: {
currentScreen = "screen2"
}
}
而且在screen2.qml:
signal changeScreen(string screen)
Button {
text: "Go To Main"
onClicked: {
changeScreen("main")
}
}
這在某種程度上工作,但緩慢/越野車。這可能是由於其他小問題,所以我接受了你的答案。 – Phat