// 导入 QtQuick 2.2 模块
import QtQuick 2.2
// 定义一个 Rectangle 组件,作为下拉菜单的容器
Rectangle {
id: dropdown // 下拉菜单的 ID
x: 0 // x 坐标
y: 0 // y 坐标
z: 0 // z 坐标
width: 458 // 宽度
height: 60 // 高度
radius: 8 // 圆角半径
color: "transparent" // 背景颜色
border.color: "#DDDDDD" // 边框颜色
border.width: 1 // 边框宽度
// 定义两个属性:当前选中的索引和图片资源数组
property int currentIndex: 1
property var imageSources: []
// 显示当前选中的图片
Image {
id: dropdownImage
source: dropdown.imageSources[dropdown.currentIndex] // 图片资源
anchors.horizontalCenter: dropdown.horizontalCenter // 水平居中
anchors.verticalCenter: dropdown.verticalCenter // 垂直居中
width: 80 // 宽度
height: 46 // 高度
z: 1 // z 坐标
}
// 显示下拉箭头
Image {
id: dropdownArrow
source: dropdown.imageSources[0] // 图片资源
anchors.right: dropdown.right // 右对齐
anchors.rightMargin: 10 // 右边距
anchors.verticalCenter: dropdown.verticalCenter // 垂直居中
width: 26 // 宽度
height: 22 // 高度
z: 2 // z 坐标
MouseArea {
anchors.fill: parent // 填充父容器
onClicked: {
dropdownMenu.visible =!dropdownMenu.visible // 点击时切换菜单的可见性
}
}
}
// 监听 imageSources 属性的变化
onImageSourcesChanged: {
for (var i = 1; i < dropdown.imageSources.length; i++) {
dropdownModel.append({imageSource: dropdown.imageSources[i]}) // 将图片资源添加到模型中
}
}
// 定义菜单容器
Rectangle {
id: dropdownMenuWrapper
clip: true // 剪辑子项
width: dropdown.width // 宽度
height: (dropdown.imageSources.length - 1) * 46 // 高度
y: dropdown.height // y 坐标
color: "transparent" // 背景颜色
border.color: "#DDDDDD" // 边框颜色
border.width: 0 // 边框宽度
z: -2 // z 坐标
radius: 5 // 圆角半径
// 定义菜单
ListView {
id: dropdownMenu
width: dropdown.width // 宽度
visible: false // 初始不可见
z: -10 // z 坐标
model: ListModel {
id: dropdownModel
Component.onCompleted: {
}
}
onVisibleChanged: {
if (visible) {
showAnimation.start() // 显示动画
dropdownMenuWrapper.border.width = 1 // 显示边框
} else {
hideAnimation.start() // 隐藏动画
dropdownMenuWrapper.border.width = 0 // 隐藏边框
}
}
delegate: Rectangle {
id: rect
color: "transparent" // 背景颜色
radius: 5 // 圆角半径
width: dropdown.width * 0.95 // 宽度
anchors.horizontalCenter: parent.horizontalCenter // 水平居中
height: 46 // 高度
Image {
source: imageSource // 图片资源
anchors.left: parent.left // 左对齐
cache: true // 缓存图片
}
MouseArea {
anchors.fill: parent // 填充父容器
onClicked: {
dropdown.currentIndex = index + 1 // 点击时更新当前选中的索引
dropdownMenu.visible = false // 隐藏菜单
}
onPressed: {
parent.color = "#cccccc" // 按下时更新背景颜色
}
onReleased: {
parent.color = "transparent" // 释放时更新背景颜色
}
}
}
// 显示动画
PropertyAnimation {
id: showAnimation
target: dropdownMenu
property: "height"
from: 0
to: (dropdown.imageSources.length - 1) * 46
duration: 200
}
// 隐藏动画
PropertyAnimation {
id: hideAnimation
target: dropdownMenu
property: "height"
from: (dropdown.imageSources.length - 1) * 46
to: 0
duration: 200
}
}
}
}
效果
给这数组赋值,图片的高度是46的图片。这里是空数组,需要你给这个数组赋值
你可以把这个文件放入一个qml文件里面,然后使用这个问题就像这样,图片最少是两个,第一个图片是右侧的下拉。之后的图片是下拉的内容