QML之Loader
import QtQuick 2.0
Item {
width: 200; height: 200
Loader { id: pageLoader }
MouseArea {
anchors.fill: parent
onClicked: pageLoader.source = "Page1.qml"
}
}
Using a Loader within a View Delegate
Item {
width: 400
height: 400
Component {
id: myComponent
Text { text: index } //fails
}
ListView {
anchors.fill: parent
model: 5
delegate: Component {
id: delegateComponent
Loader {
sourceComponent: myComponent
}
}
}
}
这种用法是错的,在Component中不能识别index。可以做以下改动
In this situation we can either move the component inline,
delegate: Component {
Loader {
sourceComponent: Component {
Text { text: index } //okay
}
}
}
into a separate file,
delegate: Component {
Loader {
source: "MyComponent.qml" //okay
}
}
异步创建
Loader {
source: "mycomponent.qml"
asynchronous: true
visible: status == Loader.Ready
}
主要为了防止在请求数据的时候,卡界面。
JS方法
使用Component的createObject
// loading the Note Component
Component {
id: noteComponent
Note { }
}
// creting an Item type that will be used as a note container
// we anchor the container to fill the parent as it will be used
// later in the code to control the dragging area for notes
Item { id: container; anchors.fill: parent }
// a Javascript helper function for creating Note QML objects
function newNoteObject(args) {
// setting the container property of the note to the
// actual container see Note.qml what the container
// property is used for
args.container = container
// calling the createObject() function on the noteComponent
// for creating Note objects.
// the container will be the parent of the new object
// and args as the set of arguments
var note = noteComponent.createObject(container, args)
if (note == null) {
console.log("note object failed to be created!")
}
}
Qt.createComponent() + Qt.createObject() 主要用于同步创建:
function sync_create()
{
var component = Qt.createComponent("page.qml", root);
if (component.status === Component.Ready)
component.createObject(root).destroy(1000);
}
Qt.createComponent() + Qt.incubateObject() 主要用于异步创建:
function async_create()
{
var finishCreation = function()
{
if (component.status === Component.Ready)
{
print("Async Create Component Success")
var incubator = component.incubateObject(root);
if (incubator.status !== Component.Ready)
{
incubator.onStatusChanged = function(status)
{
if (status === Component.Ready)
{
print("Async Create Object Success")
incubator.object.destroy(1000);
}
}
}
}
}
var component = Qt.createComponent("page.qml", Component.Asynchronous, root);
if (component.status === Component.Ready)
{
print("Async Create Component Ready")
finishCreation();
}
else
{
print("Async Create Component Not Ready")
component.statusChanged.connect(finishCreation);
}
}