QML Training Course II QML语法

QML 语法

QML结构 是基于 元素的层次结构.

每个子元素从 parent 继承位置.

Parent元素: Rectangle

Children元素: MouseArea 和 Text

chileren元素的x,y position继承自其parent元素,即x, y位置相同.

Properties

  • 每个QML元素, 都有 很多元素属性(width, radius, font.pixelSize, border.width, model, delegate, etc)
  • 定义 新属性: property :     Ex: property int count: 0
  • QML中的类型有: var, int, real, string, bool, double, url, color, font, etc
  • 声明属性的另一种方法是使用 别名alias. property alias :
  • alias别名属性 允许 forward 其它的属性或者object. Ex: property alias buttonText: textItem.text

Id property

  • id 是element的唯一标识, 就像 object name
  • id 不是必须的
  • 如果想access object的properties, 则id 有用.

Positioning

  • 使用x和y坐标来定位 object. 使用z来指定layout的顺序

QML Training Course II QML语法_第1张图片

  • 使用 anchors  锚 来放置object. anchors允许以另一个element来放置一个element.

 

Positioning elements

  • 按Row排序, 将child items 要么从左到右, 或者从右到左 一个接着一个排序; 从左到右, 或者从右到左 取决于layoutDirection 属性

QML Training Course II QML语法_第2张图片

Row {
    spacing: 10
    height: 20
  
    Text {
        text: "Label"
    }
  
    CheckBox {
        checked: false
    }
}

 

  • 按Column排序, child items 从一列一个接着一个往下排.

QML Training Course II QML语法_第3张图片

 

Column {
    spacing: 10
   width: 200
    Rectangle {
        width: parent.width
        height: 20
        color: "red"
    }
  
    Rectangle {
        width: parent.width
        height: 20
        color: "yellow"
    }
}
  • spacing 属性, 间距属性, 用来表示 chile elements之间的距离.

例子

SwitchButton.qml

import QtQuick 2.0

Item {
    id: switchButton

    property string leftText
    property string rightText

    signal leftClicked()
    signal rightClicked()

    onLeftClicked: {
        console.log("inside");
        leftButton.color = "yellow";
        rightButton.color = "#FFFFFF";
    }

    onRightClicked: {
        rightButton.color = "yellow";
        leftButton.color = "#FFFFFF";
    }

}

ButtonExample.qml

import QtQuick 2.8
import QtQuick.Window 2.2

Window {
    id: mainView
    

    Rectangle {
        id: settingsArea
        anchors.bottom: parent.bottom
        width: parent.width
        height: 150
        color: "#39393A"
        radius: 3

        Column {
            height: 100
            anchors.verticalCenter: parent.verticalCenter
            anchors.right: parent.right
            anchors.rightMargin: 30
            spacing: 10

            SwitchButton {
                rightText: "Right"
                leftText: "Left"

                onLeftClicked: {
                    console.log("Outside");
                    circle.x = 0;
                }

                onRightClicked: {
                    circle.x = (mainView.width - circle.width);
                }
            }

        }
    }
}

SwitchButton.qml 里面的 onLeftClicked 比 ButtonExample.qml 里面的onLeftClicked 先一步执行.

你可能感兴趣的:(Qt,qt)