QML 教程 1 - 值类型

第一个程序是一个非常简单的 "Hello world "示例,介绍了一些基本的 QML 概念。下图是该程序的截图。

下面是该程序的 QML 代码:

import QtQuick

Rectangle {
    id: page
    width: 320; height: 480
    color: "lightgray"

    Text {
        id: helloText
        text: "Hello world!"
        y: 30
        anchors.horizontalCenter: page.horizontalCenter
        font.pointSize: 24; font.bold: true
    }
}

演练

导入

首先,我们需要导入本例所需的类型。大多数 QML 文件都会导入 Qt XML 自带的内置 QML 类型(如Rectangle,Image, ...),使用:

import QtQuick

矩形类型

Rectangle {
    id: page
    width: 320; height: 480
    color: "lightgray"

我们声明一个Rectangle 类型的根对象。它是用 QML 创建应用程序的基本构件之一。我们给它一个id ,以便以后引用。在本例中,我们称它为 "page"。我们还设置了widthheightcolor 属性。Rectangle 类型包含许多其他属性(如xy ),但这些属性都保持默认值。

文本类型

    Text {
        id: helloText
        text: "Hello world!"
        y: 30
        anchors.horizontalCenter: page.horizontalCenter
        font.pointSize: 24; font.bold: true
    }

我们添加一个Text 类型作为根矩形类型的子类型,该类型显示文本 "Hello world!"。

y 属性用于将文本垂直定位在距父代顶部 30 像素的位置。

anchors.horizontalCenter 属性指的是类型的水平中心。在本例中,我们指定文本类型在页面元素中水平居中(请参阅 "基于锚点的布局")。

font.pointSizefont.bold 属性与字体有关,使用点符号。

查看示例

要查看创建的内容,请运行qml 工具(位于bin 目录中),并将文件名作为第一个参数。例如,要从安装位置运行所提供的已完成教程 1 示例,可键入

qml tutorials/helloworld/tutorial1.qml

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.