如2个QML文件,下
//SquareButton.qml import QtQuick 2.2 Rectangle{ width:100;height:100;color:"red"; MouseArea{ anchors.fill:parent onClicked:console.log("Button clicked"); } }由于文件名称是SquareButton.qml,因此可以被同一目录下的其他QML文件作为SqureButton类型使用。如
//myapplication.qml import QtQuick 2.2 SquareButton{}当myapplication.qml文档被引擎加载时,它会将SquareButton.qml作为一个组件进行加载,并对其实例化来创建一个SquareButton对象。QML引擎从这个类型实例出一个SquareButton对象。
如SquareButton.qml文件的根对象类型是Rectangle,这意味着在Rectangle类型中定义的所有的属性都可以被SquareButton对象修改。
所有的SquareButton都可以使用上面定义的pressd属性、buttonClicked信号、randomizeColor()方法。 如:
import QtQuick 2.0 SquareButton{ id:squareButton; onButtonClicked:{ console.log("Clicked",xPos,yPos); randomizeColor() } Text { text:squareButton.pressed?"Down":"Up"; } }SquareButton.qml中定义的任何一个id值都不能在SquareButton对象中进行访问。因为id只能在组件作用域中进行访问。