使用Component类型
除了使用单独的QML文件,还可以使用Component类型在一个
QML文档中定义一个组件。
如:
import QtQuick 2.2
Item {
width:100;height:100
//定义的Component必须包含一个唯一的根对象
//如这里是Rectangle
Component {
id:redSquare;
Rectangle{
color:"red";
width:10;
height:10
}
}
Loader{
sourceComponent:redSquare;
}
Loader{
sourceComponent:redSquare;x:20
}
}
Component类型一般是为视图提供图形组件,如ListView::delegate属性需要一个Component指定它的每一个列表项需要怎么样显示。
还可以使用Qt.createComponent()来创建Component。Component创建上下文(context)对应于Component声明处的上下文。当一个组件被ListView或Loader这样对象实例化之后,这个上下文就是父对象的上下文。
本文介绍了如何在QML中使用Component类型定义和复用组件,包括直接在QML文档内定义Component,以及如何通过Loader实例化这些组件。此外还提到了Component在ListView中的应用。

1643

被折叠的 条评论
为什么被折叠?



