基本元素 (Basic Elements)
- 基本元素有「可視」與「不可視」兩種
- 這些基本元素,就是要拼湊出畫面的基礎建設。想像一下,如果我想要做一支票漂亮亮的視窗應用程式,我會需要哪些東西?
- 大概就是想要畫出有顏色的幾何圖形、想要寫字、想要放圖片上去,利用這些形形色色的元素,建設出畫面。如果我想畫個矩形,這個圖形應該擺在哪呢?要畫多大?這個圖形跟那個圖形的相對位置關係?
- 在行為方面,我也可能需要「當滑鼠點擊到這個矩形時」做點什麼變化。又或者當某個元素發生改變時,我也要做一點什麼有趣的事情。又或者是,需要用一個計時器來處理某些事務或產生效果之類的。
- 基本元素有
- 矩形框元素 (Rectangle Element)
- 文本元素 (Text Element)
- 圖像元素(Image Element)
- 鼠標區域元素 (MouseArea Element)
- QML真的很棒!在我看來,它已經將使用者介面設計必要的需求以及可能發生的行為,考慮的蠻詳盡了!
- Item 是所有可視化元素的基礎物件,所有其它的可視化元素都繼承自 Item
- 原文有一個 Item 元素的屬性(也就是所有可視化元素共同擁有的屬性) 分類表,其實也不需要去記憶有什麼分類,我在想應該是在做UI時候,腦袋裡想到要畫什麼、做什麼事情,大概按「意義」稍微想像一下就會知道該從哪裡挖....
- Geometry (幾何屬性)
- Layout handling (布局操作)
- Key handlikng (按鍵操作)
- Transformation(轉換)
- Visual(可視化)
- State definition (狀態定義)
- 想要了解各式各樣的元素,它們有什麼屬性可以讓你利用,隨時上Qt官網看看說明文件
- 以下做了一張圖,上面一排是 Basic Elements,下面一排是這些元素都會有的共同屬性的分類

下面看一下原文給的範例程式碼,讀起來還蠻直覺的....
- 矩形框元素(Rectangle Element)
Rectangle {
id: rect1
x: 12; y: 12
width: 76; height: 96
color: "lightsteelblue"
}
Rectangle {
id: rect2
x: 112; y: 12
width: 76; height: 96
border.color: "lightsteelblue"
border.width: 4
radius: 8
}
- 填充的顏色與矩形的邊框也支持自定義的漸變色
Rectangle {
id: rect1
x: 12; y: 12
width: 176; height: 96
gradient: Gradient {
GradientStop { position: 0.0; color: "lightsteelblue" }
GradientStop { position: 1.0; color: "slategray" }
}
border.color: "slategray"
}
- 文本元素(Text Element)
Text {
text: "The quick brown fox"
color: "#303030"
font.family: "Ubuntu"
font.pixelSize: 28
}
- 圖像元素(Image Element)
Image {
x: 12; y: 12
// width: 48
// height: 118
source: "assets/rocket.png"
}
Image {
x: 112; y: 12
width: 48
height: 118/2
source: "assets/rocket.png"
fillMode: Image.PreserveAspectCrop
clip: true
}
- 鼠標區域元素 (MouseArea Element)
Rectangle {
id: rect1
x: 12; y: 12
width: 76; height: 96
color: "lightsteelblue"
MouseArea {
id: area
width: parent.width
height: parent.height
onClicked: rect2.visible = !rect2.visible
}
}
Rectangle {
id: rect2
x: 112; y: 12
width: 76; height: 96
border.color: "lightsteelblue"
border.width: 4
radius: 8
}
組件 (Compontents)
- 你可以用一些元素集合組成一個組件(元件),這個組件就可以重複利用。就好像定義了一種新的元素型別
- 原文中的範例,就是做了一個 Button 的組件
// Button.qml
import QtQuick 2.0
Rectangle {
id: root
// export button properties
property alias text: label.text
signal clicked
width: 116; height: 26
color: "lightsteelblue"
border.color: "slategrey"
Text {
id: label
anchors.centerIn: parent
text: "Start"
}
MouseArea {
anchors.fill: parent
onClicked: {
root.clicked()
}
}
}
- 之後要用 Button 元素的時候只要在QML程式碼中宣告一下就可使用了
Button { // our Button component
id: button
x: 12; y: 12
text: "Start"
onClicked: {
status.text = "Button clicked!"
}
}
Text { // text changes when button was clicked
id: status
x: 12; y: 76
width: 116; height: 26
text: "waiting ..."
horizontalAlignment: Text.AlignHCenter
}