写项目的时候发现,qml自带的comboBox在样式和功能上都不能满足我的要求,所以,干脆直接自己写了一个comboBox,想怎么设置都可以,为所欲为。
代码
Rectangle {
id:comboBox
property alias currentIndex: listviewer.currentIndex //把currentInedx提出来,方便外部调用
property alias currentText: currentext.text
property string currentname: "" //初始状态下,comboBox显示的内容,看需求自定义
property int listheight: 100 //listview的长度和listelement的长度
property int listelementheight: 30
property var items: [ //listview的代理项目
{ target: "" }
]
width: 180;
height: 50;
smooth:true;
Rectangle {
id:chosenItem
color: t_background_color //我在main的全局变量里自定义的风格颜色
border.color: Qt.rgba(0.7725, 0.7725, 0.7725, 1.0)
border.width: 1
radius:4;
width:parent.width;
height:comboBox.height;
smooth:true;
Text {
id:currentext
color: t_color
width: parent.width-parent.height
height: parent.height
text: comboBox.currentname
font.family: "Arial" //字体
font.pointSize: parent.height/3
smooth:true
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
visible: true; //可见
}
//下拉按钮
Button{
width: height
height: parent.height
anchors.right: parent.right
background: Rectangle{
color: t_background_color
border.color: Qt.rgba(0.7725, 0.7725, 0.7725, 1.0)
border.width: 1
}
Text {
id: icon
text: qsTr("\uf150") //调用图标库,怎么调用可以看我的另一篇博客,自定义spinBox里
font.family: "fontawesome"
color: t_color
anchors.centerIn: parent
font.pixelSize: parent.height
anchors.right: parent.right
}
}
MouseArea {
width: comboBox.width / 18 * 40
height: comboBox.height / 3
anchors.bottomMargin: 0
anchors.fill: parent;
onClicked: {
comboBox.state = comboBox.state==="dropDown"?"":"dropDown" //控制下拉和回收
}
}
}
Rectangle{
id:dropDown
width:comboBox.width;
height:0;
clip:true;
radius:4;
anchors.top: chosenItem.bottom;
anchors.margins: comboBox.height / 9
color: t_background_color
border.color: Qt.rgba(0.8627, 0.8627, 0.8627, 1.0)
border.width: 1
ListView{
id:listviewer
height: comboBox.listheight;
model: comboBox.items
currentIndex: 0;
delegate: Rectangle{
id: listbg
width: comboBox.width
height: comboBox.listelementheight;
color: ListView.isCurrentItem ? "lightblue" : "#00333333" //设置当前选择项高亮
Text {
text: modelData.target
font.pixelSize: listbg.height
anchors.fill: parent
color: t_color;
elide: Text.ElideRight
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
}
MouseArea {
anchors.fill: parent;
onClicked: {
comboBox.state = ""
currentext.text = modelData.target;
listviewer.currentIndex = index;
}
}
}
}
Scrolbar{
target: listviewer
}
}
//设置下拉动画
//状态列表
states: State {
name: "dropDown";
PropertyChanges { target: dropDown; height:listviewer.height}
}
//转换列表
transitions: Transition {
NumberAnimation { target: dropDown; properties: "height"; easing.type: Easing.OutExpo; duration: 1000 }
}
}
调用
MycomboBox{
anchors.bottom: parent.bottom
anchors.bottomMargin: 500
anchors.right: parent.right
anchors.rightMargin: 350
width: 400
height: 50
listheight: 130
listelementheight: 30
currentname: "开局一只鲲"
items: [
{target:"唱跳"},
{target:"Rap"},
{target:"篮球"},
{target:"律师函警告"}
]
}
效果