QML的核心特性之一是能够通过QML文档轻松地以轻量级方式定义QML对象类型,以适应各个QML应用程序的需求。标准Qt Quick模块提供了各种类型,如矩形、文本和图像,用于构建QML应用程序;除此之外,您还可以轻松地定义自己的QML类型,以便在应用程序中重用。这种创建自己类型的能力构成了任何QML应用程序的构建块。
要创建对象类型,应该将QML文档放在名为 .qml 的文本文件中,其中 是类型的所需名称。类型名称有以下要求。
然后引擎自动将该文档识别为QML类型的定义。此外,在解析QML类型名称时,引擎在直接目录中搜索时,以这种方式定义的类型可自动用于同一目录中的其他QML文件。这种其实就是通过相对路径来访问的模块。
例如,下面是一个文档,它声明了一个具有子鼠标区域的矩形。文档已经保存到文件SquareButton.qml中:
// SquareButton.qmlimport QtQuick 2.0Rectangle {property int side: 100width: side; height: sidecolor: "red"MouseArea {anchors.fill: parentonClicked: console.log("Button clicked!")}}
因为文件名为 SquareButton.qml,这现在可以被同一目录中的任何其他qml文件用作名为 SquareButton 的类型。例如,如果有一个myapplication。在同一个目录下的qml文件中,它可以引用SquareButton类型:
// myapplication.qmlimport QtQuick 2.0SquareButton {}

这创建了一个100 x 100的红色矩形,内有一个鼠标区,定义在 SquareButton.qml 中。当我的应用程序。引擎加载qml文档,加载SquareButton。qml文档作为一个组件,并实例化它以创建一个 SquareButton 对象。
SquareButton 类型封装了 SquareButton.qml 中声明的QML对象树。当QML引擎从这个类型实例化一个SquareButton对象时,它是从SquareButton. QML中声明的矩形树实例化一个对象。
注意:在某些文件系统(尤其是UNIX)上,文件名的字母大小写是重要的。建议文件名的大小写与所需的QML类型名称的大小写完全匹配,例如Box。qml而不是BoX。qml -无论qml类型将部署到哪个平台。
如果SquareButton。QML和我的应用程序不在同一个目录下。在qml中,SquareButton类型需要通过myapplication.qml中的import语句来指定。它可以从文件系统的相对路径导入,也可以作为一个已安装的模块;更多细节请参见模块。
.qml 文件中的根对象定义定义了QML类型可用的属性。属于这个根对象的所有属性、信号和方法——无论是自定义声明的,还是来自根对象的QML类型的——都是外部可访问的,并且可以为这种类型的对象读取和修改。
例如,SquareButton中的根对象类型。上面的qml文件是矩形的。这意味着可以为SquareButton对象修改由Rectangle类型定义的任何属性。
下面的代码定义了三个SquareButton对象,它们为类型为SquareButton的根Rectangle对象的某些属性定义了自定义值:
// application.qmlimport QtQuick 2.0Column {SquareButton { side: 50 }SquareButton { x: 50; color: "blue" }SquareButton { radius: 10 }}

自定义QML类型的对象可访问的属性包括为对象额外定义的任何自定义属性、方法和信号。例如,假设SquareButton中的矩形。QML定义如下,具有额外的属性、方法和信号:
// SquareButton.qmlimport QtQuick 2.0Rectangle {id: rootproperty bool pressed: mouseArea.pressedsignal buttonClicked(real xPos, real yPos)function randomizeColor() {root.color = Qt.rgba(Math.random(), Math.random(), Math.random(), 1)}property int side: 100width: side; height: sidecolor: "red"MouseArea {id: mouseAreaanchors.fill: parentonClicked: root.buttonClicked(mouse.x, mouse.y)}}
任何SquareButton对象都可以使用添加到根矩形上的pressed属性、buttonClicked信号和randomizeColor()方法:
// application.qmlimport QtQuick 2.0SquareButton {id: squareButtononButtonClicked: {console.log("Clicked", xPos, yPos)randomizeColor()}Text { text: squareButton.pressed ? "Down" : "Up" }}
注意SquareButton中定义的任何id值。SquareButton对象不能访问qml,因为id值只能在声明组件的组件范围内访问。
上面定义的SquareButton对象不能引用mouseArea来引用mouseArea子对象,而且如果它的id是root而不是SquareButton,就不会与SquareButton中定义的root对象的id发生冲突。QML作为两者将在单独的作用域内声明。