qml Loader中setSource方法的使用 举例
时间: 2024-02-11 17:09:05 浏览: 27
好的,下面是一个使用setSource方法的例子:
假设我们有两个QML文件:Main.qml和OtherComponent.qml,其中OtherComponent.qml是一个自定义组件,我们想要在Main.qml中动态地加载OtherComponent.qml。
Main.qml中的代码如下:
```
import QtQuick 2.0
Item {
id: mainItem
Loader {
id: componentLoader
anchors.fill: parent
}
Button {
text: "Load OtherComponent.qml"
onClicked: {
componentLoader.setSource("OtherComponent.qml");
}
}
}
```
上述代码中,我们创建了一个Loader组件,将其作为Main.qml的子组件,并将其大小设置为与父组件相同。在按钮的点击事件中,我们调用了Loader组件的setSource方法,并将参数设置为"OtherComponent.qml",表示要加载的QML文件名。
OtherComponent.qml的代码如下:
```
import QtQuick 2.0
Rectangle {
id: otherComponent
width: 200
height: 200
color: "red"
Text {
text: "This is OtherComponent.qml"
anchors.centerIn: parent
}
}
```
上述代码中,我们定义了一个红色的矩形,并在其中添加了一个居中显示的文本。
当我们在Main.qml中点击"Load OtherComponent.qml"按钮时,Loader组件会动态加载OtherComponent.qml文件,并将其作为Loader的子组件添加到Main.qml中。这时,我们就可以看到OtherComponent.qml中定义的矩形和文本了。
这就是一个简单的使用setSource方法的例子,希望能对你有所帮助。