采用 QML 的第一步

创建 QML 文档

QML 文档采用高度可读、结构化布局定义对象层次结构。每个 QML 文档由 2 个部分组成:导入章节和对象声明章节。用户界面的最常见类型和功能的提供在 QtQuick 导入。

导入和使用 QtQuick 模块

要使用 Qt Quick 模块,QML 文档需要导入它。import 句法看起来像这样:

import QtQuick
					

类型和功能的 Qt Quick 提供现在可用于 QML 文档!

定义对象层次结构

QML 文档中的对象声明定义将在视觉场景中显示什么。 Qt Quick 提供用于所有用户界面的基本构建块 (譬如:用于显示图像、文本及用于处理用户输入的对象)。

A simple object declaration might be a colored window with some text centered in it:

Window {
    width: 640
    height: 480
    visible: true
    color: "red"
    Text {
        anchors.centerIn: parent
        text: "Hello, World!"
    }
}
					

这定义对象层次结构采用根 Window 对象,其拥有子级 文本 对象。 parent 文本 对象被自动设置到 Window ,和同样, 文本 对象被添加到 children 特性为 Window 对象,通过 QML。

全部放在一起

The Window and 文本 类型用于以上范例, 两者的提供通过 QtQuick 导入。将 import 和对象声明放在一起,得到完整 QML 文档:

import QtQuick
Window {
    width: 640
    height: 480
    visible: true
    color: "red"
    Text {
        anchors.centerIn: parent
        text: "Hello, World!"
    }
}
					

若将该文档另存为 HelloWorld.qml,可以加载并显示它。

创建和运行 QML 工程

要显示由 QML 文档定义的图形场景,可能加载它采有 Qt Creator . To create a new QML project in Qt Creator:

  1. 选择 File > New Project > Qt Quick Application 从 Qt Creator 中。
  2. Enter a name for your project and select a location to save it.
  3. Select the appropriate Qt version and optionally configure version control settings for the project.
  4. Review the summary of your project settings and continue to complete the project build.

When finished, Qt Creator will generate the necessary files and open the project for development. Pressing the green 运行 按钮运行应用程序。应该见到文本 Hello, World! 在红色矩形中心。

有关在 Qt Creator 中创建和运行工程的更多信息,拜访以下页面:

采用控件创建 QML 应用程序

虽然 Qt Quick 提供基本图形元素, Qt Quick Controls 提供现成的 QML 类型以供在应用程序中使用。

插入 ApplicationWindow 类型是创建应用程序的很好起点。应用程序 UI 拥有这种基本布局:

在各区域内,不同 controls 可以添加并连接以形成应用程序。例如,以下代码片段是演示可用空间用法的基本应用程序:

//import related modules
import QtQuick
import QtQuick.Controls
//window containing the application
ApplicationWindow {
    width: 640
    height: 480
    visible: true
    //title of the application
    title: qsTr("Hello World")
    //menu containing two menu items
    header: MenuBar {
        Menu {
            title: qsTr("&File")
            Action {
                text: qsTr("&Open...")
                onTriggered: console.log("Open action triggered")
            }
            MenuSeparator { }
            Action {
                text: qsTr("&Exit")
                onTriggered: Qt.quit()
            }
        }
    }
    //Content Area
    //a button in the middle of the content area
    Button {
        text: qsTr("Hello World")
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.verticalCenter: parent.verticalCenter
    }
}
					

应用程序拥有 2 菜单项和中间按钮。点击 Exit 菜单项关闭应用程序。

还有不同导航方法和不同控件 (譬如:按钮和滑块)。以下范例是可用的从 Qt Creator 并演示不同控件及布局。

Feel free to copy and paste the snippets onto this simple Hello World application to see how QML works.

处理用户输入

使用 QML 定义用户界面的一大优势是它允许用户界面设计者定义应用程序应如何采用简单 JavaScript 表达式对事件做出反应。在 QML 中,我们引用这些事件作为 signals 和这些信号被处理通过 信号处理程序 .

例如,考虑以下范例:

import QtQuick
Window {
    id: root
    width: 200
    height: 100
    color: isRed ? "red" : "blue"
    visible: true
    property bool isRed: true  // Track the color state
    Text {
        anchors.centerIn: parent
        text: "Hello, World!"
    }
    TapHandler {
        onTapped: root.isRed = !root.isRed  // Toggle state
    }
}
					

This example can be saved as "ClickableHelloWorld.qml" and run with qml QML Runtime Tool . Whenever the user clicks anywhere in the window, the rectangle will change from red to blue. Tapping again will change it back to red.

注意: TapHandler 还为触摸事件发射敲击信号,因此此代码也工作于移动设备。

可以采用简单表达式处理类似键盘用户输入:

import QtQuick
Window {
    id: root
    width: 200
    height: 100
    color: "red"
    visible: true
    Text {
        id: myText
        anchors.centerIn: parent
        text: toggle ? "Hello, World!" : "Goodbye, World!"
        focus: true
        property bool toggle: true
        Keys.onReturnPressed: (event)=>{
            myText.toggle = !myText.toggle;
            event.accepted = true;
        }
    }
}
					

Now, each time you press the Enter key, the text will alternate between "Hello, World" and "Goodbye, World".

特性绑定

对象及其特性形成 QML 文档定义的图形界面基础。QML 语言允许特性以各种方式相互绑定,使用户界面能够高动态。

在以下范例中,几何体对于每个子级 Rectangle 被绑定到父级 Window 。若几何体对于父级 Window object were to change, the geometry of each child Rectangle 将自动更新由于特性绑定。

import QtQuick
Window {
    id: root
    width: 200
    height: 100
    color: "red"
    visible: true
    Rectangle {
        width: root.width / 2
        height: root.height
        color: "blue"
    }
    Rectangle {
        width: root.width / 2
        height: root.height
        x: root.width / 2
        color: "green"
    }
}
					

动画

特性还可以动态更新凭借动画。 QtQuick import 提供各种动画类型,可用于动画改变特性值。在以下范例中,特性被动画化,然后显示在 文本 区域:

import QtQuick
Window {
    id: root
    width: 200
    height: 100
    color: "red"
    visible: true
    property int animatedValue
    SequentialAnimation on animatedValue {
        loops: Animation.Infinite
        PropertyAnimation {
            to: 150
            duration: 1000
        }
        PropertyAnimation {
            to: 0
            duration: 1000
        }
    }
    Text {
        anchors.centerIn: parent
        text: root.animatedValue
    }
}
					

显示值会周期性地从 0 到 150 变化。

定义自定义 QML 类型以供重用

最重要的 QML 概念之一是类型重用。应用程序可能拥有完全相似的多个可视化类型 (例如:多个按钮),且 QML 允许将这些种类的东西定义为可重用的自定义类型,以最小化代码重复及最大化可读性。

例如,想象开发者定义新的 MessageLabel 类型在 MessageLabel.qml 文件:

// MessageLabel.qml
import QtQuick
Rectangle {
    height: 50
    property string message: "debug message"
    property var msgType: ["debug", "warning" , "critical"]
    color: "black"
    Column {
        anchors.fill: parent
        padding: 5.0
        spacing: 2
        Text {
            text: msgType.toString().toUpperCase() + ":"
            font.bold: msgType == "critical"
            font.family: "Terminal Regular"
            color: msgType === "warning" || msgType === "critical" ? "red" : "yellow"
            ColorAnimation on color {
                running: msgType == "critical"
                from: "red"
                to: "black"
                duration: 1000
                loops: msgType == "critical" ? Animation.Infinite : 1
            }
        }
        Text {
            text: message
            color: msgType === "warning" || msgType === "critical" ? "red" : "yellow"
            font.family: "Terminal Regular"
        }
    }
}
					

现在可以在应用程序中多次重用该类型,如下所示:

// application.qml
import QtQuick
Window {
    id: root
    width: 180
    height: 180
    visible: true
    Column {
        anchors.fill: parent
        padding: 1.5
        topPadding: 10.0
        bottomPadding: 10.0
        spacing: 5
        MessageLabel{
            width: root.width - 2
            msgType: "debug"
        }
        MessageLabel {
            width: root.width - 2
            message: "This is a warning!"
            msgType: "warning"
        }
        MessageLabel {
            width: root.width - 2
            message: "A critical warning!"
            msgType: "critical"
        }
    }
}
								

按此方式,模块化用户界面类型在应用程序中被组装及重用。

QML 对象属性 了解如何开发自己可重用组件的更多有关细节。

从这里开始

现在您已见到 QML 的作用,准备迈出下一步。以下页面将引导您踏上 QML 之旅。