2. 使用Rectangle和Text组件

任务目标

使用QML中的Rectangle和Text组件,创建一个包含矩形背景和文本标签的简单界面,并掌握颜色、尺寸及文本内容的设置方法。

环境准备

需要Qt 5.15或更高版本(含Qt Quick模块)。创建Qt Quick Application项目,或在现有项目中新建.qml文件并配置QML运行环境。

关键完整代码

以下代码可直接保存为main.qml,通过qmlscene main.qml或Qt Creator运行:

```qml import QtQuick 2.15 Rectangle { width: 400 height: 300 color: "#2E3440" // 深蓝灰色背景 Rectangle { id: card width: 200 height: 120 radius: 8 anchors.centerIn: parent color: "#88C0D0" // 浅蓝色卡片 Text { id: titleText anchors.top: parent.top anchors.topMargin: 20 anchors.horizontalCenter: parent.horizontalCenter text: "Hello QML" color: "#2E3440" font.pixelSize: 24 font.bold: true } Text { id: subText anchors.bottom: parent.bottom anchors.bottomMargin: 15 anchors.horizontalCenter: parent.horizontalCenter text: "Rectangle + Text" color: "#4C566A" font.pixelSize: 14 } } } ```

运行与验证

  1. 将上述代码保存为main.qml。
  2. 在终端执行qmlscene main.qml(需确保qmlscene在PATH中),或直接在Qt Creator中打开运行。
  3. 预期窗口显示:深蓝灰色背景中央有一个圆角浅蓝色矩形卡片,卡片上方显示加粗的“Hello QML”,下方显示较小字号的“Rectangle + Text”。

通过条件:窗口正常打开且无QML语法错误;矩形颜色、圆角、尺寸与代码设置一致;两行文本内容、字号、颜色及相对位置正确。

关键点说明

  • Rectangle的color支持十六进制或颜色名称;radius控制圆角大小。
  • Text的text属性直接设置显示内容,font.pixelSize与font.bold控制字体样式。
  • 使用anchors进行相对定位,anchors.centerIn: parent使卡片居中,子文本通过top/bottom锚定在卡片内部。