这可能是因为第一次加载后,Loader组件已经包含了要切换的QML文件,再次设置source属性时并不会重新加载该文件。为了解决这个问题,可以在每次切换前先清除Loader组件的内容。
以下是修改后的示例代码:
// MainPage.qml
import QtQuick 2.0
Rectangle {
id: mainPage
width: 400
height: 400
// 显示当前页内容
Loader {
id: contentLoader
anchors.fill: parent
source: "MainContent.qml"
}
// 点击按钮切换到第二个页面
Button {
text: "Switch to Second Page"
onClicked: {
// 在切换前先清空Loader内容
contentLoader.item = null;
contentLoader.source = "SecondContent.qml";
}
anchors.centerIn: parent
}
}
// SecondPage.qml
import QtQuick 2.0
Rectangle {
id: secondPage
width: 400
height: 400
// 显示当前页内容
Loader {
id: contentLoader
anchors.fill: parent
}
Component.onCompleted: {
// 第一次加载时显示默认页面
contentLoader.source = "SecondContent.qml";
}
// 点击按钮返回到第一个页面
Button {
text: "Back to Main Page"
onClicked:{
// 在切换前先清空Loader内容
contentLoader.item = null;
contentLoader.source = "MainContent.qml";
}
anchors.centerIn: parent
}
}
在上述代码中,我们使用了Loader组件的item属性,通过将其设置为null来清空Loader组件的内容。同时,在第二页中增加了一个Component.onCompleted事件处理程序,用于在第一次加载时显示默认页面。
这样修改后,每次切换时都会重新加载指定的QML文件。