QML学習(三)——
10807 ワード
QMLオブジェクト宣言
QMLオブジェクトのプロパティは、一般的に次の順序で構築されます. id 属性宣言 信号宣言 JavaScript関数 オブジェクト属性 サブオブジェクト 状態 状態切替 より読みやすいように、異なる部分の間に空の行を追加することをお勧めします.たとえば、次の例としてPhotoオブジェクトを使用します.
属性グループ
1つの属性のセットで複数の属性が使用されている場合は、ポイント表現ではなくグループ表現を使用すると、可読性が向上します.例:
リスト#リスト#
リストに要素が1つしか含まれていない場合は、通常、四角カッコは無視されます.たとえば、次のコードがあります.
次のように書くことができます.
JavaScriptコード
スクリプトが別の式の場合は、次のように直接使用することをお勧めします.
スクリプトが数行しかない場合は、次のように書くことをお勧めします.
スクリプトに多くのローがある場合や、異なるオブジェクトで使用する必要がある場合は、次のように関数を作成して呼び出すことをお勧めします.
長いスクリプトの場合は、この関数を独立したJavaScriptファイルに配置し、次のようにインポートできます.
QMLオブジェクトのプロパティは、一般的に次の順序で構築されます.
1 Rectangle {
2 id: photo // id ,
3
4 property bool thumbnail: false //
5 property alias image: photoImage.source
6
7 signal clicked //
8
9 function doSomething(x) // javascript
10 {
11 return x + photoImage.width
12 }
13
14 color: "gray" //
15 x: 20; y: 20; height: 150 //
16 width: { //
17 if (photoImage.width > 200) {
18 photoImage.width;
19 } else {
20 200;
21 }
22 }
23
24 Rectangle { //
25 id: border
26 anchors.centerIn: parent; color: "white"
27
28 Image { id: photoImage; anchors.centerIn: parent }
29 }
30
31 states: State { //
32 name: "selected"
33 PropertyChanges { target: border; color: "red" }
34 }
35
36 transitions: Transition { //
37 from: ""; to: "selected"
38 ColorAnimation { target: border; duration: 200 }
39 }
40 }
属性グループ
1つの属性のセットで複数の属性が使用されている場合は、ポイント表現ではなくグループ表現を使用すると、可読性が向上します.例:
1 Rectangle {
2 anchors.left: parent.left; anchors.top: parent.top;
3 anchors.right: parent.right; anchors.leftMargin: 20
4 }
5
6 Text {
7 text: "hello"
8 font.bold: true; font.italic: true; font.pixelSize: 20;
9 font.capitalization: Font.AllUppercase
10 }
11 :
12
13 Rectangle {
14 anchors { left: parent.left; top: parent.top; right: parent.right; leftMargin: 20 }
15 }
16
17 Text {
18 text: "hello"
19 font { bold: true; italic: true; pixelSize: 20; capitalization: Font.AllUppercase }
20 }
リスト#リスト#
リストに要素が1つしか含まれていない場合は、通常、四角カッコは無視されます.たとえば、次のコードがあります.
states: [
State {
name: "open"
PropertyChanges { target: container; width: 200 }
}
]
次のように書くことができます.
states: State {
name: "open"
PropertyChanges { target: container; width: 200 }
}
JavaScriptコード
スクリプトが別の式の場合は、次のように直接使用することをお勧めします.
Rectangle { color: "blue"; width: parent.width / 3 }
スクリプトが数行しかない場合は、次のように書くことをお勧めします.
Rectangle {
color: "blue"
width: {
var w = parent.width / 3
console.debug(w)
return w
}
}
スクリプトに多くのローがある場合や、異なるオブジェクトで使用する必要がある場合は、次のように関数を作成して呼び出すことをお勧めします.
function calculateWidth(object)
{
var w = object.width / 3
// ...
// more javascript code
// ...
console.debug(w)
return w
}
Rectangle { color: "blue"; width: calculateWidth(parent) }
長いスクリプトの場合は、この関数を独立したJavaScriptファイルに配置し、次のようにインポートできます.
import "myscript.js" as Script
Rectangle { color: "blue"; width: Script.calculateWidth(parent) }