第 1 课:让窗口里出现一个居中的方块和文字
更新: 10/23/2026 字数: 0 字 时长: 0 分钟
打开你项目里的 Main.qml,把内容先替换成下面这样:
qml
import QtQuick
import QtQuick.Window
Window {
width: 640
height: 480
visible: true
title: "第一课"
Rectangle {
width: 200
height: 100
color: "lightblue"
anchors.centerIn: parent
Text {
text: "Hello QML"
anchors.centerIn: parent
font.pixelSize: 24
}
}
}然后按 Ctrl + R,或者点 Qt Creator 左下角的绿色三角运行。
你应该会看到一个窗口,中间有一个浅蓝色矩形,矩形中间写着 Hello QML。
逐行理解
1. import QtQuick
导入 QML 基础类型,比如:
RectangleTextItemMouseArea
没有它,这些类型都不能用。
2. import QtQuick.Window
导入窗口类型 Window。
3. Window
这是顶层窗口。
qml
width: 640
height: 480
visible: true
title: "第一课"width:窗口宽height:窗口高visible: true:必须写,不然窗口不显示title:窗口标题
4. Rectangle
一个矩形可视元素。
qml
width: 200
height: 100
color: "lightblue"- 宽 200,高 100
- 颜色浅蓝
5. anchors.centerIn: parent
锚点居中,意思是:
把自己放在父元素的正中间。
这里的父元素是 Window,所以矩形在窗口中间。
6. Text
文本元素。
qml
text: "Hello QML"
anchors.centerIn: parent
font.pixelSize: 24text:显示的文字anchors.centerIn: parent:文字在矩形中间font.pixelSize: 24:字体大小 24
你的动手练习
现在不要急着学下一课,先把这几个练习做完。
练习 1
把文字改成:
text
我是 QML 新手练习 2
把矩形颜色改成红色,可以用:
qml
color: "tomato"或者:
qml
color: "#FF6347"练习 3
把矩形大小改成:
qml
width: 300
height: 150练习 4
给矩形加圆角:
qml
radius: 20练习 5
把矩形从“居中”改成“左上角,离窗口边缘 20 像素”。
提示:去掉:
qml
anchors.centerIn: parent换成:
qml
anchors.left: parent.left
anchors.top: parent.top
anchors.margins: 20