QML 可以多选ComboBox的实现
由于项目需要,需要设计一个可以多选的ComboBox,看了一下文档,发现QML自带的ComboBox确实无法多选。看了一下ComboBox的实现,发现弹出的下拉菜单是用Menu实现的,看来只能自己重写了,毕竟Menu本身就是无法多选的!代码不多,直接看实现吧!
importQtQuick2.5importQtQuick.Controls1.4importQtQuick.Controls.Styles1.4Item{id:rootimplicitWidth:150implicitHeight:30propertyaliasmodel:lv.modelpropertyvarindexs:[]propertyvarm_text:""functionremoveValue(arr,val){//删除数组中指定的内容arr数组,val内容for(vari=0;i<arr.length;i++){if(arr[i]==val){arr.splice(i,1)returnarr;}}}Button{id:btnanchors.fill:parentText{anchors.fill:parentanchors.margins:5anchors.rightMargin:30text:m_texthorizontalAlignment:Text.AlignHCenterverticalAlignment:Text.AlignVCenterfont.pointSize:12clip:trueelide:Text.ElideMiddle}onClicked:{sv.visible=!sv.visible;}Image{anchors.right:parent.rightanchors.top:parent.topwidth:root.heightheight:root.heightsource:"换成自己下拉按钮图片"}}Component{id:m_delRectangle{id:rectcolor:"white"implicitWidth:150implicitHeight:30propertyboolisSelect:falseText{anchors.fill:parenthorizontalAlignment:Text.AlignHCenterverticalAlignment:Text.AlignVCenterfont.pointSize:15text:label}MouseArea{anchors.fill:parenthoverEnabled:trueonEntered:{if(!isSelect){rect.color="#CDDCFE";}}onExited:{if(!isSelect){rect.color="white"}}onClicked:{rect.isSelect=!rect.isSelect;if(!rect.isSelect){//取消某项rect.color="white"//删除文本中指定的字符串vararr=m_text.split(",");arr=removeValue(arr,label)m_text=arr.join(",");//删除数组中记录指定的内容indexs=removeValue(indexs,index);}else{//选择某项rect.color="#F9E977"if(m_text.length==0){m_text+=label;}else{m_text+=","+label;}indexs.push(index)}}}}}ScrollView{id:svanchors.top:btn.bottomanchors.left:parent.leftwidth:parent.widthheight:300visible:falseListView{id:lvdelegate:m_delanchors.fill:parent}}}
有个地方和官方的ComboBox有些区别,就是需要点击按钮才会将下拉列表收起来,不知道怎样才能实现点击其他位置,关闭下拉列表,有知道的朋友告诉我一声,谢啦!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。