qml ComboBox 组合框

ComboBox 组合框

在QML(Qt Meta Language)中,ComboBox是一种常用的用户界面元素,

用于让用户从一组预定义的选项中选择一个。

ComboBox通常由一个文本输入框和一个下拉列表组成,

用户可以点击文本输入框来展开下拉列表,然后从中选择一个选项。

属性:

c++ 复制代码
model:

类型: var
描述: 定义ComboBox的选项列表。可以是数组、ListModel或其他可迭代的数据源。
示例:
ComboBox {
    model: ["Option 1", "Option 2", "Option 3"]
}

currentIndex:

类型: int
描述: 当前选中的选项的索引。
示例:
ComboBox {
    model: ["Option 1", "Option 2", "Option 3"]
    currentIndex: 1  // 默认选中第二个选项
}

currentText:

类型: string
描述: 当前选中的选项的文本。
示例:
ComboBox {
    model: ["Option 1", "Option 2", "Option 3"]
    onCurrentTextChanged: console.log("Current text:", currentText)
}

editable:

类型: bool
描述: 是否允许用户编辑文本输入框。
示例:
ComboBox {
    model: ["Option 1", "Option 2", "Option 3"]
    editable: true
}

textRole:

类型: string
描述: 当模型是一个对象列表时,指定显示在ComboBox中的文本属性。
示例:
ListModel {
    id: comboModel
    ListElement { name: "Option 1"; value: 1 }
    ListElement { name: "Option 2"; value: 2 }
}
ComboBox {
    model: comboModel
    textRole: "name"
}

displayText:

类型: string
描述: 显示在ComboBox输入框中的文本。可以用于自定义显示文本。
示例:
ComboBox {
    model: ["Option 1", "Option 2", "Option 3"]
    displayText: "Select an option"
}

count:

类型: int
描述: ComboBox中选项的总数。
示例:
ComboBox {
    model: ["Option 1", "Option 2", "Option 3"]
    onCountChanged: console.log("Total options:", count)
}

方法:

c++ 复制代码
selectAll():

描述: 选中ComboBox输入框中的所有文本。
示例:
ComboBox {
    model: ["Option 1", "Option 2", "Option 3"]
    editable: true
    MouseArea {
        anchors.fill: parent
        onClicked: comboBox.selectAll()
    }
}

incrementCurrentIndex():

描述: 将currentIndex增加1。
示例:
ComboBox {
    model: ["Option 1", "Option 2", "Option 3"]
    Keys.onRightPressed: incrementCurrentIndex()
}

decrementCurrentIndex():

描述: 将currentIndex减少1。
示例:
ComboBox {
    model: ["Option 1", "Option 2", "Option 3"]
    Keys.onLeftPressed: decrementCurrentIndex()
}

forceActiveFocus():

描述: 强制ComboBox获得焦点。
示例:
ComboBox {
    model: ["Option 1", "Option 2", "Option 3"]
    MouseArea {
        anchors.fill: parent
        onClicked: comboBox.forceActiveFocus()
    }
}

事件:

c++ 复制代码
onActivated:

描述: 当用户选择一个选项时触发。
示例:
ComboBox {
    model: ["Option 1", "Option 2", "Option 3"]
    onActivated: console.log("Selected index:", index)
}

onCurrentIndexChanged:

描述: 当currentIndex改变时触发。
示例:
ComboBox {
    model: ["Option 1", "Option 2", "Option 3"]
    onCurrentIndexChanged: console.log("Current index:", currentIndex)
}

onCurrentTextChanged:

描述: 当currentText改变时触发。
示例:
ComboBox {
    model: ["Option 1", "Option 2", "Option 3"]
    onCurrentTextChanged: console.log("Current text:", currentText)
}

自定义绘制

c++ 复制代码
import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Controls.Basic 2.15
import Qt5Compat.GraphicalEffects

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    color: "#f0f0f0"

    ComboBox {
        id: control
        model: ["First", "Second", "Third"]

        // 自定义委托,用于显示下拉框中的每一项
        delegate: ItemDelegate {
            id: delegate

            // 必需的属性,用于访问模型数据和索引
            required property var model
            required property int index

            width: control.width
            contentItem: Text {
                text: delegate.model[control.textRole]  // 显示模型中的文本
                color: "#21be2b"  // 文本颜色
                font: control.font  // 使用ComboBox的字体
                elide: Text.ElideRight  // 文本过长时省略号显示
                verticalAlignment: Text.AlignVCenter  // 垂直居中对齐
            }
            highlighted: control.highlightedIndex === index  // 高亮当前选中的项
        }

        // 自定义指示器,用于显示下拉箭头
        indicator: Canvas {
            id: canvas
            x: control.width - width - control.rightPadding  // 定位到右侧
            y: control.topPadding + (control.availableHeight - height) / 2  // 垂直居中
            width: 12
            height: 8
            contextType: "2d"

            // 连接ComboBox的pressedChanged信号,当按下状态改变时重新绘制指示器
            Connections {
                target: control
                function onPressedChanged() { canvas.requestPaint(); }
            }

            // 绘制指示器
            onPaint: {
                context.reset();
                context.moveTo(0, 0);
                context.lineTo(width, 0);
                context.lineTo(width / 2, height);
                context.closePath();
                context.fillStyle = control.pressed ? "#17a81a" : "#21be2b";  // 按下时改变颜色
                context.fill();
            }
        }

        // 自定义内容项,用于显示当前选中的文本
        contentItem: Text {
            leftPadding: 0
            rightPadding: control.indicator.width + control.spacing  // 右侧留出指示器的空间

            text: control.displayText  // 显示当前选中的文本
            font: control.font  // 使用ComboBox的字体
            color: control.pressed ? "#17a81a" : "#21be2b"  // 按下时改变颜色
            verticalAlignment: Text.AlignVCenter  // 垂直居中对齐
            elide: Text.ElideRight  // 文本过长时省略号显示
        }

        // 自定义背景,用于显示ComboBox的背景和边框
        background: Rectangle {
            implicitWidth: 120
            implicitHeight: 40
            border.color: control.pressed ? "#17a81a" : "#21be2b"  // 按下时改变边框颜色
            border.width: control.visualFocus ? 2 : 1  // 有焦点时加粗边框
            radius: 2  // 圆角半径
        }

        // 自定义弹出框,用于显示下拉列表
        popup: Popup {
            y: control.height - 1  // 定位到ComboBox下方
            width: control.width
            implicitHeight: contentItem.implicitHeight
            padding: 1

            // 弹出框的内容项,使用ListView显示下拉列表
            contentItem: ListView {
                clip: true  // 裁剪超出部分
                implicitHeight: contentHeight  // 根据内容高度调整高度
                model: control.popup.visible ? control.delegateModel : null  // 仅在弹出框可见时显示模型
                currentIndex: control.highlightedIndex  // 高亮当前选中的项

                // 添加垂直滚动条
                ScrollIndicator.vertical: ScrollIndicator { }
            }

            // 弹出框的背景
            background: Rectangle {
                color: "black"  // 设置背景矩形的颜色
                border.color: "red"  // 设置背景矩形的边框颜色
                border.width: 1  // 设置背景矩形的边框宽度
                radius: 4  // 设置背景矩形的圆角半径

                // 添加阴影效果
                layer.enabled: true  // 启用图层
                layer.effect: DropShadow {
                    horizontalOffset: 0  // 设置水平阴影偏移
                    verticalOffset: 2  // 设置垂直阴影偏移
                    radius: 8.0  // 设置阴影半径
                    samples: 16  // 设置阴影采样数
                    color: "#80000000"  // 设置阴影颜色
                }
            }
        }
    }
}
相关推荐
子兮曰16 分钟前
AI 浏览器 Agent 的安全困局:当自动化工具可以偷走你的登录态
前端·人工智能·后端
程序员黑豆22 分钟前
鸿蒙应用开发之@Styles 装饰器:定义可复用的组件样式
前端·harmonyos
程序员码歌24 分钟前
我全程用 AI开发了一款微信小游戏,上线了
android·前端·游戏开发
咩咩啃树皮25 分钟前
第52篇:前端工程化完整体系精讲——Vite构建、模块化、打包原理、规范体系、面试终极通关
前端·面试·职场和发展
妙码生花26 分钟前
从 PHP 到 AI + Golang,程序员自救转型手记(四十八):菜单规则管理实现
前端·后端·ai编程
FogLetter28 分钟前
当JavaScript学会“分身术”:异步编程的进化简史
前端·javascript·面试
hunterandroid1 小时前
[鸿蒙从零到一] HarmonyOS 分布式能力与设备协同实战:从发现设备到任务闭环
前端
lichenyang4531 小时前
从图片创作到本地可复现的 AIGC 全栈闭环:AIGC Creative Studio 实践复盘
前端·后端
牧艺1 小时前
别急着 Vibe Coding:AI 三小时写完需求后,我为什么宁愿多花一天
前端·agent·vibecoding
java1234_小锋1 小时前
Vue3+Vite简介以及构建第一个HelloWorld实例
前端·javascript·vue.js·vite