QML組件是由基本元素組合成的一個複雜的可重用的組合元素。QML 提供了多種方法來建立組件。ide
基於文件的組件將QML元素放置在一個單獨的文件中,而後給文件一個名字,能夠經過名字來使用組件。若是有一個文件名爲Cell.qml,就能夠在QML中使用Cell { … }形式。自定義組件的文件名的首字母必須大寫。ui
Cell.qml文件:spa
import QtQuick 2.0 Item { id: container property alias cellColor: rectangle.color signal clicked(color cellColor) width: 40; height: 25 Rectangle { id: rectangle border.color: "white" anchors.fill: parent } MouseArea { anchors.fill: parent onClicked: container.clicked(container.cellColor) } }
Rectangle有一個Text用於顯示按鈕的文本;有一個MouseArea用於接收鼠標事件。用戶能夠定義按鈕的文本,用過設置Text的text屬性實現的。爲了避免對外暴露Text元素,給Text的text屬性一個別名。signal clicked給Cell一個信號。因爲clicked信號是無參數的,也能夠寫成signal clicked(),兩者是等價的。clicked信號會在MouseArea的clicked信號被髮出,具體就是在MouseArea的onClicked屬性中調用個clicked信號。component
Main.qml文件:blog
import QtQuick 2.0 Rectangle { id: page width: 320; height: 480 color: "lightgray" Text { id: helloText text: "Hello world!" y: 30 anchors.horizontalCenter: page.horizontalCenter font.pointSize: 24; font.bold: true } Grid { id: colorPicker x: 4; anchors.bottom: page.bottom; anchors.bottomMargin: 4 rows: 2; columns: 3; spacing: 3 Cell { cellColor: "red"; onClicked: helloText.color = cellColor } Cell { cellColor: "green"; onClicked: helloText.color = cellColor } Cell { cellColor: "blue"; onClicked: helloText.color = cellColor } Cell { cellColor: "yellow"; onClicked: helloText.color = cellColor } Cell { cellColor: "steelblue"; onClicked: helloText.color = cellColor } Cell { cellColor: "black"; onClicked: helloText.color = cellColor } } }
main.qml中,直接使用了Cell組件。因爲Cell.qml與main.qml位於同一目錄下,因此不須要額外的操做。但若是將Cell.qml放在不一樣目錄,main.qml的import部分增長一行import ../components纔可以找到Cell組件。事件
選擇一個組件的根元素很重要。好比Cell組件,使用Rectangle做爲其根元素。Rectangle元素能夠設置背景色等。若是不容許用戶設置背景色,能夠選擇使用Item元素做爲根。圖片