自訂群組件
在qml檔案中自訂群組件可以分為全域自訂群組件和內嵌自訂群組件
全域自訂群組件定義在一個單獨的qml檔案中,檔案名稱即組件名(這點是c++程式員開始比較迷惑的地方,實際上java的檔案名稱和類名也是如此),首字母預設會轉化為大寫,類似Item、Text等。
下面自訂一個組件,每秒會自己變幻背景色,我們稱之為閃光燈FlashLight,儲存為FlashLight.qml
import QtQuick 2.7import QtQuick.Controls 2.0Rectangle { 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.7import QtQuick.Controls 2.0Rectangle { 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.7import QtQuick.Controls 2.0Rectangle { 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 自訂屬性
property type name: value
自訂訊號
sigal name([type arg1,type arg2,...])
動態建立
除了上述以檔案名稱建立組件和以Loader通過id或者檔案路徑載入組件外,QT還提供了兩個JS方法來建立組件
1、使用 Qt.createComponent() 動態地建立一個組件對象,然後使用 Component 的 createObject() 方法建立對象
2、使用 Qt.createQmlObject() 從一個 QML 字串直接建立一個對象
關於這兩種方法的參數和使用可以查閱協助手冊