參考:QML Tutorial 2 - QML Components - Qt for Python
為了避免多次編寫(xiě)相同的代碼辛友,可以創(chuàng)建 QML 組件导盅。組件提供了定義新類(lèi)型的方法,可以在其他 QML 文件中重用這種類(lèi)型讥电。
QML 組件就像一個(gè)黑盒女仰,通過(guò)屬性猜年、信號(hào)和函數(shù)與外部世界進(jìn)行交互,通常在它自己的 QML 文件中定義疾忍。組件的文件名必須總是以大寫(xiě)字母開(kāi)頭乔外。
// Cell.qml
import QtQuick 2.0
Item {
id: container
property alias cellColor: rectangle.color
signal clicked(cellColor: color)
width: 40; height: 25
Rectangle {
id: rectangle
border.color: "white"
anchors.fill: parent
}
MouseArea {
anchors.fill: parent
onClicked: container.clicked(container.cellColor)
}
}
組件的根類(lèi)型是帶有 id
容器的 Item。
Item
是 QML 中最基本的視覺(jué)類(lèi)型一罩,通常用作其他類(lèi)型的容器杨幼。
聲明 cellColor
屬性。這個(gè)屬性可以從組件外部訪問(wèn),這允許我們用不同的顏色實(shí)例化單元格差购。這個(gè)屬性只是現(xiàn)有屬性的別名—組成單元格的矩形的顏色(參見(jiàn) Property Binding)补疑。
的組件也有一個(gè)信號(hào),調(diào)用 click
時(shí)帶有一個(gè)類(lèi)型為 color
的 cellColor
參數(shù)歹撒。稍后,將使用這個(gè)信號(hào)來(lái)更改主 QML 文件中的文本的顏色诊胞。
Cell
組件基本上是帶有 id
的彩色矩形暖夭。
anchors.fill
屬性是設(shè)置可視類(lèi)型大小的方便方法。在這種情況下撵孤,矩形的大小將與其父矩形相同迈着。
為了在單擊單元格時(shí)改變文本的顏色,創(chuàng)建 MouseArea 類(lèi)型邪码,其大小與其父單元格相同裕菠。
MouseArea
定義了稱(chēng)為 clicked
的信號(hào)。當(dāng)這個(gè)信號(hào)被觸發(fā)時(shí)闭专,我們想要發(fā)出我們自己的點(diǎn)擊信號(hào)奴潘,并將顏色作為參數(shù)。
下面這 main QML 中使用 Cell
:
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 }
}
}
當(dāng)單元格的點(diǎn)擊信號(hào)被觸發(fā)時(shí)影钉,我們希望將文本的顏色設(shè)置為作為參數(shù)傳遞的 cellColor
画髓。可以通過(guò)名為“onSignalName”的屬性對(duì)組件的任何信號(hào)做出反應(yīng)(參見(jiàn) Signal Attributes)平委。