2. 使用QML基本元素布局界面
任务目标
使用QML基本元素(Rectangle、Text、Image)结合锚布局(anchors),构建一个静态的“音乐播放器”界面。界面包含顶部标题栏、中部专辑封面区域、底部控制按钮区,所有元素位置通过锚布局自动适配,不依赖坐标。
环境依赖
需要Qt 5.15+或Qt 6.x开发环境,安装Qt Quick模块。创建Qt Quick Application工程后,将以下代码替换main.qml全部内容,并准备一张本地图片作为专辑封面(示例使用cover.jpg,放置于工程目录)。
关键完整代码
import QtQuick 2.15
import QtQuick.Window 2.15
Window {
width: 360
height: 640
visible: true
title: "Music Player"
color: "#1e1e2e"
// 根容器:全窗口锚定
Rectangle {
anchors.fill: parent
color: "transparent"
// 顶部标题栏
Rectangle {
id: titleBar
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
height: 56
color: "#2a2a3e"
Text {
anchors.centerIn: parent
text: "Now Playing"
font.pixelSize: 18
font.bold: true
color: "#ffffff"
}
}
// 中部专辑封面区域
Rectangle {
id: coverArea
anchors.top: titleBar.bottom
anchors.left: parent.left
anchors.right: parent.right
anchors.bottom: controlBar.top
color: "transparent"
// 封面图片
Image {
id: coverImage
anchors.centerIn: parent
width: 220
height: 220
source: "cover.jpg"
fillMode: Image.PreserveAspectCrop
clip: true
// 圆角遮罩
Rectangle {
anchors.fill: parent
radius: 12
color: "transparent"
border.color: "#ffffff"
border.width: 2
}
}
// 歌曲名称
Text {
id: songTitle
anchors.top: coverImage.bottom
anchors.topMargin: 20
anchors.horizontalCenter: parent.horizontalCenter
text: "Midnight City"
font.pixelSize: 20
font.bold: true
color: "#ffffff"
}
// 歌手名称
Text {
id: artistName
anchors.top: songTitle.bottom
anchors.topMargin: 6
anchors.horizontalCenter: parent.horizontalCenter
text: "M83"
font.pixelSize: 14
color: "#a0a0b0"
}
}
// 底部控制按钮区
Rectangle {
id: controlBar
anchors.bottom: parent.bottom
anchors.left: parent.left
anchors.right: parent.right
height: 80
color: "#2a2a3e"
// 上一首按钮
Text {
id: prevButton
anchors.left: parent.left
anchors.leftMargin: 40
anchors.verticalCenter: parent.verticalCenter
text: "⏮"
font.pixelSize: 28
color: "#ffffff"
}
// 播放/暂停按钮
Text {
id: playButton
anchors.centerIn: parent
text: "▶"
font.pixelSize: 36
color: "#ffcc66"
}
// 下一首按钮
Text {
id: nextButton
anchors.right: parent.right
anchors.rightMargin: 40
anchors.verticalCenter: parent.verticalCenter
text: "⏭"
font.pixelSize: 28
color: "#ffffff"
}
}
}
}
运行与验证
运行方式:在Qt Creator中打开工程,确保cover.jpg位于工程根目录(或修改source为实际路径),点击运行按钮(或使用qmlscene main.qml命令)。
验证方法:
- 窗口尺寸为360×640,背景为深色(#1e1e2e)。
- 顶部出现56像素高的标题栏,文字“Now Playing”水平垂直居中。
- 中部显示220×220的封面图片,图片下方依次显示“Midnight City”和“M83”,均水平居中。
- 底部80像素高的控制栏中,播放按钮(▶)位于水平中央,上一首(⏮)和下一首(⏭)分别位于左右两侧,间距40像素。
- 拖动窗口边缘改变大小,各元素相对位置保持不变(锚布局生效)。
通过条件:界面元素完整显示、无锚布局警告(控制台无“Unable to anchor”类错误)、窗口缩放时元素间距比例正常。