【QML】QML自定义ComboBox

1. 效果

在这里插入图片描述

2. 代码

import QtQuick 2.15
import QtQuick.Controls 2.15

ComboBox {
    id: control
    property real popHeight: 0

    // 右侧下拉箭头
    indicator: Canvas {
        id: canvas
        x: control.width - width - control.rightPadding;
        y: control.topPadding + (control.availableHeight - height) / 2;
        width: 20;
        height: 12;
        contextType: "2d";

        onPaint: {
            var ctx = getContext("2d")
            ctx.reset();
            ctx.moveTo(0, 0);

            ctx.lineWidth = 3;
            ctx.lineTo(width / 2, height*0.8);
            ctx.lineTo(width, 0);
            ctx.strokeStyle = control.enabled ? "black" : "grey"
            ctx.stroke();
        }
    }

    contentItem: Text {     //界面上显示出来的文字
        leftPadding: 20      //左部填充为5
        text: control.displayText   //表示ComboBox上显示的文本
        font: control.font          //文字大小
        color: control.enabled ? "black" : "grey"   //control.pressed ?
        verticalAlignment: Text.AlignVCenter        //文字位置
    }

    background: Rectangle {   //背景项
        implicitWidth: 120
        implicitHeight: 40
        property string sColor: control.enabled ? "white" : "lightgrey"
        color: control.pressed ? Qt.darker(sColor, 1.2) : sColor
        border.width: 1
        border.color: "lightgrey"
        radius: 0
    }

    popup: Popup {    //弹出项
        y: control.height
        width: control.width
        implicitHeight: control.popHeight === 0 ? contentItem.implicitHeight : control.popHeight
        padding: 1

        //istView具有一个模型和一个委托。模型model定义了要显示的数据
        contentItem: ListView {   //显示通过ListModel创建的模型中的数据
            clip: true
            implicitHeight: contentHeight
            model: control.popup.visible ? control.delegateModel : null
        }

        background: Rectangle {
            border.color: "black"
            radius: 2
        }

        onAboutToHide: {
            canvas.rotation = 0
        }

        onAboutToShow: {
            canvas.rotation = 180
        }
    }

    delegate: ItemDelegate { //呈现标准视图项 以在各种控件和控件中用作委托
        width: control.width
        contentItem: Text {
            text: modelData   //即model中的数据
            color: "black"
            font: control.font
            verticalAlignment: Text.AlignVCenter
        }
    }
}

  • 18
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值