在qml文件中自定义组件可以分为全局自定义组件和内嵌自定义组件
全局自定义组件定义在一个单独的qml文件中,文件名即组件名(这点是c++程序员开始比较迷惑的地方,实际上java的文件名和类名也是如此),首字母默认会转化为大写,类似Item、Text等。
下面自定义一个组件,每秒会自己变幻背景色,我们称之为闪光灯FlashLight,保存为FlashLight.qml
import QtQuick 2.7 import QtQuick.Controls 2.0 Rectangle { id: flash; property int time : 1000; radius: 10 width: 20 height: 20 Timer { id: timer; interval: time; repeat: true; running: true; triggeredOnStart: true; onTriggered: { flash.color = Qt.rgba(Math.random(), Math.random(), Math.random(), 1); } } onTimeChanged: { timer.interval = time; } onRadiusChanged: { width = radius*2; height = radius*2; } }上述就是一个自定义组件,单独定义在一个qml文件中,它有一个顶层元素是Rectangle,相当于继承自Rectangle,所以也拥有了Rectangle的所有属性和方法,在另外的qml文件中调用它很简单,通过其文件名即可,如下所示
import QtQuick 2.7 import QtQuick.Controls 2.0 Rectangle { width: 640; height: 480; color: "#DCDCDC" FlashLight { anchors.centerIn: parent radius: 100; time: 100; } }直接使用FlashLight ,就和使用Rectangle一样,这里设定了它的属性半径是100,时间是100ms变幻一次颜色,time是我们自定义的一个属性,自定义属性的格式是property type name: value
内嵌组件相当于内嵌类的概念,只有当前文件作用域能够使用它,一般声明形式如下:
import QtQuick 2.7 import QtQuick.Controls 2.0 Rectangle { width: 100; height: 100; color: "#FFF8DC"; radius: 10; border.width: 10; border.color: "#FAEBD7"; Component { id: circle; Rectangle { width: 20; height: 20; radius: 10; color: "#FF0000" } } Loader { id: one; sourceComponent: circle; anchors.centerIn: parent; visible: true; } Loader { id: two; sourceComponent: circle; anchors.centerIn: parent; visible: false; } Loader { id: three; sourceComponent: circle; anchors.centerIn: parent; visible: false; } Loader { id: four; sourceComponent: circle; anchors.centerIn: parent; visible: false; } Loader { id: five; sourceComponent: circle; anchors.centerIn: parent; visible: false; } Loader { id: six; sourceComponent: circle; anchors.centerIn: parent; visible: false; } property int num: 1 onNumChanged: { one.visible = false; two.visible = false; three.visible = false; four.visible = false; five.visible = false; six.visible = false; switch(num){ case 1: one.visible = true; break; case 2: two.visible = true; break; case 3: three.visible = true; break; case 4: four.visible = true; break; case 5: five.visible = true; break; case 6: six.visible = true; break; } } }其中id为circle的就是一个内嵌组件,内嵌组件以Component进行定义,给定一个id,Loader是以动态加载的方式在使用它,使用sourceComponent来指定id
除了上述以文件名创建组件和以Loader通过id或者文件路径加载组件外,QT还提供了两个JS方法来创建组件
1、使用 Qt.createComponent() 动态地创建一个组件对象,然后使用 Component 的 createObject() 方法创建对象 2、使用 Qt.createQmlObject() 从一个 QML 字符串直接创建一个对象
关于这两种方法的参数和使用可以查阅帮助手册
ithewei 认证博客专家 c/c Qt libhv 编程之路,其路漫漫,吾将上下而求索https://github.com/itheweihttps://hewei.blog.csdn.net