// 导入 QtQuick 2.2 模块
import QtQuick 2.2// 定义一个 Rectangle 组件,作为下拉菜单的容器
Rectangle {id: dropdown // 下拉菜单的 IDx: 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: 1property var imageSources: []// 显示当前选中的图片Image {id: dropdownImagesource: dropdown.imageSources[dropdown.currentIndex] // 图片资源anchors.horizontalCenter: dropdown.horizontalCenter // 水平居中anchors.verticalCenter: dropdown.verticalCenter // 垂直居中width: 80 // 宽度height: 46 // 高度z: 1 // z 坐标}// 显示下拉箭头Image {id: dropdownArrowsource: 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: dropdownMenuWrapperclip: 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: dropdownMenuwidth: dropdown.width // 宽度visible: false // 初始不可见z: -10 // z 坐标model: ListModel {id: dropdownModelComponent.onCompleted: {}}onVisibleChanged: {if (visible) {showAnimation.start() // 显示动画dropdownMenuWrapper.border.width = 1 // 显示边框} else {hideAnimation.start() // 隐藏动画dropdownMenuWrapper.border.width = 0 // 隐藏边框}}delegate: Rectangle {id: rectcolor: "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: showAnimationtarget: dropdownMenuproperty: "height"from: 0to: (dropdown.imageSources.length - 1) * 46duration: 200}// 隐藏动画PropertyAnimation {id: hideAnimationtarget: dropdownMenuproperty: "height"from: (dropdown.imageSources.length - 1) * 46to: 0duration: 200}}}
}
效果
给这数组赋值,图片的高度是46的图片。这里是空数组,需要你给这个数组赋值
你可以把这个文件放入一个qml文件里面,然后使用这个问题就像这样,图片最少是两个,第一个图片是右侧的下拉。之后的图片是下拉的内容