组件对于QML来说就如同C++的类一样。可以用同一个组件创建多个对象。

组件有两种定义方式:

  • 用独立的.qml文件定义组件
  • 在.qml文件中用Component对象定义组件

1. 创建项目,新建文件IndependentComponent.qml

import QtQuickRectangle {id : rootText {id: componentTextanchors.fill: parenthorizontalAlignment: Text.AlignHCenterverticalAlignment: Text.AlignVCenterfont.pixelSize: 40text: qsTr("文件定义的组件")}}

2. 编辑main.qml

import QtQuickWindow {width: 640height: 480visible: truetitle: qsTr("Hello World")Component {id : embeddedComponentRectangle {id : rootText {id: componentTextanchors.fill: parenthorizontalAlignment: Text.AlignHCenterverticalAlignment: Text.AlignVCenterfont.pixelSize: 40text: qsTr("Component定义的组件")}}}Loader {id : embeddedComponentLoadersourceComponent: embeddedComponentx : 270y : 100width: 100height: 30onLoaded: {console.log("嵌入式组件创建成功")}}IndependentComponent {x : 270y : 200width : 100height : 30}}

在独立.qml中定义组件,就是在qml文件中编写任何你需要的内容,本例写了一个Rectangle里面包含了一个Text。定义完后qml的文件名就是组件名,可以在其他qml中直接使用。比如本例在main.qml中直接使用IndependentComponent定义了第二个控件

用Component对象定义组件就是Component对象中定义任何你需要的内容。然后通过Loader对象创建组件对象。Loader通过Component对象的id来创建Component对象,本例中为embeddedComponentLoader

可以多次使用loader或IndependentComponent创建多个对象。本例中各自只创建了一个对象。

3. 运行程序