編輯:關於 Android 程式設計
上一篇已經在電腦與 Android 手機上跑通了第一個 Qt Quick 範例 HelloQtQuickApp。這篇來談談 Qt Quick 編程的一些基本概念,為日後開發更複雜的應用打底。
先回顧一下 main.qml:

檔案第一行是 import QtQuick 2.0,作用是引入 QtQuick 模組,效果等同 C++ 的 #include 或 Java 的 import。
Qt Quick 是 QML 的標準庫,提供了大量基礎元素與控制項。如果把 QML 比作 C++ 語言本身,那麼 Qt Quick 的角色就有點像 STL。
Rectangle {
width: 320;
height: 480;
color: "blue";
border.color: "#808080";
border.width: 2;
radius: 12;
}這個 Rectangle 定義了一個矩形:寬 320、高 480、填充藍色、邊框灰色粗 2、圓角半徑 12。
QML 中的顏色可以用名稱(blue、red、green、transparent)、"#RRGGBB" 或 "#AARRGGBB" 指定,也可以用 Qt.rgba()、Qt.lighter() 等方法構造。color 型別有 r、g、b、a 四個屬性:
Text {
color: "red"
Component.onCompleted: console.log(color.r, color.g, color.b, color.a) // 1 0 0 1
}漸變的型別是 Gradient,透過 GradientStop 指定顏色與位置(0.0 到 1.0),中間的色階由 QML 自動插值:
Rectangle {
width: 100;
height: 100;
gradient: Gradient {
GradientStop { position: 0.0; color: "#202020"; }
GradientStop { position: 0.33; color: "blue"; }
GradientStop { position: 1.0; color: "#FFFFFF"; }
}
}Gradient 只能做垂直方向的漸變。想要其他方向,可以搭配 rotation 屬性:
Rectangle {
width: 100;
height: 100;
rotation: 90;
gradient: Gradient {
GradientStop { position: 0.0; color: "#202020"; }
GradientStop { position: 1.0; color: "#A0A0A0"; }
}
}順帶一提,rotation 其實來自 Rectangle 的父類 Item。
Item 自己什麼都不繪製,卻定義了繪製圖形所需的絕大部分通用屬性:x、y、width、height、錨定(anchoring)、按鍵處理等。此外還有 scale、smooth、anchors、antialiasing、enabled、visible、state、states、children 等,詳見 Qt 幫助文件。
Item 可以用來「分組」其他可視元素:
import QtQuick 2.0
Rectangle {
width: 300;
height: 200;
Item {
id: gradientGroup;
Rectangle {
x: 20; y: 20; width: 120; height: 120;
gradient: Gradient {
GradientStop { position: 0.0; color: "#202020"; }
GradientStop { position: 1.0; color: "#A0A0A0"; }
}
}
Rectangle {
x: 160; y: 20; width: 120; height: 120; rotation: 90;
gradient: Gradient {
GradientStop { position: 0.0; color: "#202020"; }
GradientStop { position: 1.0; color: "#A0A0A0"; }
}
}
}
Component.onCompleted: {
console.log("visible children: ", gradientGroup.visibleChildren.length);
console.log("children: ", gradientGroup.children.length);
for (var i = 0; i < gradientGroup.children.length; i++) {
console.log("child ", i, " x = ", gradientGroup.children[i].x);
}
}
}分組後可透過 children 或 visibleChildren 屬性存取子元素。
單靠 x、y、width、height 這四個屬性做絕對坐標布局,很難適應各種手機解析度。anchors 提供了另一種思路:透過描述「我與別人的關係」來決定位置。
每個 item 都有 7 條不可見的錨線:left、horizontalCenter、top、bottom、right、verticalCenter、baseline。

baseline 主要用於文字對齊,可以想像一行文字坐在基線上。對沒有文字的圖形,baseline 與 top 一致。
除了對齊錨線,還可以指定四側留白:leftMargin、topMargin、rightMargin、bottomMargin。

import QtQuick 2.0
Rectangle {
width: 300;
height: 200;
Rectangle {
id: rect1;
anchors.left: parent.left;
anchors.leftMargin: 20;
anchors.top: parent.top;
anchors.topMargin: 20;
width: 120; height: 120;
gradient: Gradient {
GradientStop { position: 0.0; color: "#202020"; }
GradientStop { position: 1.0; color: "#A0A0A0"; }
}
}
Rectangle {
anchors.left: rect1.right;
anchors.leftMargin: 20;
anchors.top: rect1.top;
width: 120; height: 120; rotation: 90;
gradient: Gradient {
GradientStop { position: 0.0; color: "#202020"; }
GradientStop { position: 1.0; color: "#A0A0A0"; }
}
}
}效果與前面的絕對坐標版本相同,但這次的描述方式與解析度無關——這正是 anchors 的價值。對元素的引用透過 id 完成。
anchors 還有 centerIn(居中於另一元素內)與 fill(填滿某元素)等:
import QtQuick 2.0
Rectangle {
width: 300;
height: 200;
Rectangle {
color: "blue";
anchors.fill: parent;
border.width: 6;
border.color: "#888888";
Rectangle {
anchors.centerIn: parent;
width: 120; height: 120;
radius: 8;
border.width: 2;
border.color: "black";
antialiasing: true;
color: "red";
}
}
}Item 除了 x、y 還有 z 屬性,型別為 real,數值越小越靠底層,越大越靠近使用者。opacity 則是透明度,取值 0.0 到 1.0。
import QtQuick 2.0
Rectangle {
width: 300;
height: 200;
Rectangle {
x: 20; y: 20; width: 150; height: 100;
color: "#606080";
z: 0.5;
}
Rectangle {
width: 100; height: 100;
anchors.centerIn: parent;
color: "#a0c080";
z: 1;
opacity: 0.6;
}
}除了視覺效果,Z 序在實務上也有功能意義。例如圖片瀏覽器載入時要顯示 loading 圖示,就得讓它的 z 值大於圖片本身,才不會被蓋住。
所有繼承自 Item 的元素都能處理按鍵,透過附加屬性 Keys 實現。Keys 定義了針對特定按鍵的信號(如 onReturnPressed),也提供更通用的 onPressed 與 onReleased。它們的參數 event 是 KeyEvent,包含按鍵細節;若按鍵已被處理,應把 event.accepted 設為 true 以免繼續傳遞。
import QtQuick 2.0
Rectangle {
width: 300;
height: 200;
color: "#c0c0c0";
focus: true;
Keys.enabled: true;
Keys.onEscapePressed: Qt.quit();
Keys.onBackPressed: Qt.quit();
Keys.onPressed: {
switch (event.key) {
case Qt.Key_0:
case Qt.Key_1:
case Qt.Key_2:
case Qt.Key_3:
case Qt.Key_4:
case Qt.Key_5:
case Qt.Key_6:
case Qt.Key_7:
case Qt.Key_8:
case Qt.Key_9:
keyView.text = event.key - Qt.Key_0;
break;
}
}
Text {
id: keyView;
font.bold: true;
font.pixelSize: 24;
text: qsTr("text");
anchors.centerIn: parent;
}
}注意 focus: true 不可省略——否則按鍵事件不會送到這個元素。
Text 可顯示純文字或富文本(HTML 標記)。它有 font、text、color、elide、textFormat、wrapMode、horizontalAlignment、verticalAlignment 等屬性。不指定 textFormat 時預設為 Text.AutoText,會自動判斷內容型別。
import QtQuick 2.0
Rectangle {
width: 300;
height: 200;
Text {
width: 150; height: 100;
wrapMode: Text.WordWrap;
font.bold: true;
font.pixelSize: 24;
font.underline: true;
text: "Hello Blue Text";
anchors.centerIn: parent;
color: "blue";
}
}也可以只讓部分文字變色,這時就要用富文本:
text: "Hello Blue <font color=\"blue\">Text</font>"
Text 的 style 屬性提供 Text.Outline、Text.Raised、Text.Sunken 三種風格,搭配 styleColor 使用(未指定 style 時 styleColor 不生效):
import QtQuick 2.0
Rectangle {
width: 300;
height: 200;
Text {
id: normal;
anchors.left: parent.left;
anchors.leftMargin: 20;
anchors.top: parent.top;
anchors.topMargin: 20;
font.pointSize: 24;
text: "Normal Text";
}
Text {
anchors.left: normal.left;
anchors.top: normal.bottom;
anchors.topMargin: 4;
font.pointSize: 24;
text: "Raised Text";
style: Text.Raised;
styleColor: "#AAAAAA";
}
Text {
anchors.left: normal.left;
anchors.top: normal.bottom;
anchors.topMargin: 34;
font.pointSize: 24;
text: "Outline Text";
style: Text.Outline;
styleColor: "red";
}
Text {
anchors.left: normal.left;
anchors.top: normal.bottom;
anchors.topMargin: 64;
font.pointSize: 24;
text: "Sunken Text";
style: Text.Sunken;
styleColor: "#A00000";
}
}按鈕可能是 GUI 應用中最常用的控制項。QML 的 Button 類似 QPushButton,點擊時觸發 clicked() 信號。使用前需引入 import QtQuick.Controls 1.1。
import QtQuick 2.0
import QtQuick.Controls 1.1
Rectangle {
width: 300;
height: 200;
Button {
anchors.centerIn: parent;
text: "Quit";
onClicked: Qt.quit();
}
}Button 的主要屬性:
· text:按鈕文字;
· checkable:是否可勾選,可勾選時由 checked 保存狀態;
· iconName / iconSource:圖示,前者依平台圖示主題名稱載入,優先級較高;
· isDefault:是否為預設按鈕,是則按 Enter 會觸發;
· pressed:按下狀態;
· menu:為按鈕關聯一個下拉選單;
· action:關聯一個 action,可統一定義 text、tooltip、checked 等;
· activeFocusOnPress:按下時是否取得焦點,預設 false;
· style:自訂外觀,搭配 ButtonStyle 使用。
使用 ButtonStyle 需引入 QtQuick.Controls.Styles 1.1。它有 background、control、label 三個屬性:control 指向套用該樣式的按鈕本身,可讀取各種狀態;label 代表按鈕文字;background 則是一個 Component。
import QtQuick 2.0
import QtQuick.Controls 1.1
import QtQuick.Controls.Styles 1.1
Rectangle {
width: 300;
height: 200;
Button {
text: "Quit";
anchors.centerIn: parent;
style: ButtonStyle {
background: Rectangle {
implicitWidth: 70;
implicitHeight: 25;
border.width: control.pressed ? 2 : 1;
border.color: (control.hovered || control.pressed) ? "green" : "#888888";
}
}
}
}效果是:滑鼠懸停時邊框變綠,按下時邊框變粗且仍為綠色。
若多個按鈕共用同一套樣式,把它抽成 Component 會更清爽:
Component {
id: btnStyle;
ButtonStyle {
background: Rectangle {
implicitWidth: 70;
implicitHeight: 25;
color: "#DDDDDD";
border.width: control.pressed ? 2 : 1;
border.color: (control.hovered || control.pressed) ? "green" : "#888888";
}
}
}
Button {
id: openButton;
text: "Open";
anchors.left: parent.left;
anchors.leftMargin: 10;
anchors.bottom: parent.bottom;
anchors.bottomMargin: 10;
style: btnStyle;
}
Button {
text: "Quit";
anchors.left: openButton.right;
anchors.leftMargin: 6;
anchors.bottom: openButton.bottom;
style: btnStyle;
}Image 可顯示 JPG、PNG、BMP、GIF、SVG 等 Qt 支援的格式,但只能顯示靜態圖片(GIF 只顯示第一幀)。要播放動畫需用 AnimatedSprite 或 AnimatedImage。
不設定 width/height 時,Image 會採用圖片本身的尺寸;設定後圖片可能被拉伸,此時可用 fillMode 控制填充方式:
· Image.Stretch:拉伸
· Image.PreserveAspectFit:等比縮放並完整顯示
· Image.PreserveAspectCrop:等比縮放並最大化填滿,必要時裁切
· Image.Tile / TileVertically / TileHorizontally:平鋪
· Image.Pad:保持原樣不變換
預設是同步載入,大圖會卡住界面。此時可設 asynchronous: true 開啟非同步載入,並在 status 變為 Image.Ready 後隱藏等待提示。
更強的是,Image 支援直接從網路載入。source 型別是 url,可接受 http、ftp 等協議;當它偵測到是網路資源時,會自動啟用非同步載入,此時 progress(0.0–1.0)與 status 都會即時更新。
import QtQuick 2.0
Image { source: "images/yourimage.png" }import QtQuick 2.0
import QtQuick.Controls 1.1
Rectangle {
width: 480;
height: 320;
color: "#121212";
BusyIndicator {
id: busy;
running: true;
anchors.centerIn: parent;
z: 2;
}
Label {
id: stateLabel;
visible: false;
anchors.centerIn: parent;
z: 3;
}
Image {
id: imageViewer;
asynchronous: true;
cache: false;
anchors.fill: parent;
fillMode: Image.PreserveAspectFit;
onStatusChanged: {
if (imageViewer.status === Image.Loading) {
busy.running = true;
stateLabel.visible = false;
} else if (imageViewer.status === Image.Ready) {
busy.running = false;
} else if (imageViewer.status === Image.Error) {
busy.running = false;
stateLabel.visible = true;
stateLabel.text = "ERROR";
}
}
}
Component.onCompleted: {
imageViewer.source = "https://example.com/demo.jpg";
}
}這裡有幾點值得說明。asynchronous 對網路資源其實不生效(網路載入天生就是非同步的),只有載入本地大圖時才需要設。cache: false 表示不快取圖片。onStatusChanged 是信號處理器,命名遵循 on{Signal} 規則。
你可能會發現 Qt 文件中並沒有明確提到 statusChanged 信號。遇到這種情況有個訣竅:直接去 SDK 頭檔裡找。Image 對應 C++ 的 QQuickImage,其父類是 QQuickImageBase,在其中可以看到:
Q_PROPERTY(Status status READ status NOTIFY statusChanged)
Q_PROPERTY 宏用來定義 QObject 及其衍生類的屬性,這樣定義的屬性可以在 QML 中存取。這行宣告了唯讀的 status 屬性,並指明值變化時發送 statusChanged 信號——謎底揭曉。
載入過程中的畫面:

背景之所以接近黑色,是因為根元素 Rectangle 的 color 設為 "#121212"。載入完成後:

等比縮放生效,變形問題解決。不到 50 行程式碼就完成了一個網路圖片瀏覽器,這就是 Qt Quick 的效率。
BusyIndicator 用來顯示等待動畫,在耗時操作中緩解使用者的等待焦慮。running 為布爾值,true 時顯示並播放動畫;style 則用於自訂外觀。
BusyIndicator {
id: busy;
running: true;
anchors.centerIn: parent;
z: 2;
}BusyIndicator 本身只有兩個屬性,但用到的 anchors 與 z 都是從 Item 繼承而來的,可以直接使用——這也再次說明了 Item 作為基類的價值。
至此,Qt Quick 的入門內容告一段落。掌握這些之後,你應該已經能讀懂並改寫一般的 QML 文檔,開始動手做自己的應用了。
Android 學習路線(十四):Activity 生命週期之停止與重啟
正確處理停止與重啟,是 Activity 生命週期中相當關鍵的一環——它決定了使用者是否感覺到「這個 App 一直都在」,以及切換回來時進度有沒有遺失。 有幾個典型場景
Android 自訂 View 實作鬧鐘喚起並播放鈴聲
本篇介紹如何以自訂 View 呈現鬧鐘喚起頁面,並在倒數結束時停止鈴聲。畫面可包含旋轉圖示、漸變光圈、時間與日期資訊。 功能重點 中央圖片可依天氣或狀態替換。
Android 遊戲實戰:打飛機遊戲的開始選單頁
這個系列的最終目標是做出可以操作的打飛機:控制小飛機左右移動、閃避子彈、擊倒 Boss。本文完成第一步——開始選單介面。 準備工作 先把圖片資源整個複製進來。接著,任何一
Android 滾輪時間選擇器:可擴充的日期與時間 Dialog
系統內建的日期選擇器未必符合所有產品需求,因此可嘗試以 WheelView 打造滾輪式時間選擇器。這類控制項可自訂標題、顯示欄位與是否開啟長期選項,適合日期、時間與證件有