1. 程式人生 > >QML ComboBox 圖片加文字

QML ComboBox 圖片加文字

Qml 目前版本的 ComboBox,不支援設定下拉選單字型,也不支援下拉選單帶圖片。在一番搜尋加調整後,我寫成下面的程式碼,可以滿足這個功能。
只是調整字型,請見ComboxBox 調整字型

Rectangle {
    id:comboBox
    property var items: [
{ lang: "en", img: "img/European-Union-icon.png" },
{ lang: "sp", img: "img/Brazil-icon.png" },
{ lang: "fr", img: "img/Jamaica-icon.png" }
    ]
    signal comboClicked;
anchors.top: main.top; anchors.topMargin: 30; anchors.left: main.left; anchors.leftMargin: 415; width: 60; height: 60; smooth:true; Rectangle { id:chosenItem radius:4; width:parent.width; height:comboBox.height; smooth:true; Image { id: main_img;
fillMode: Image.PreserveAspectFit source: "image/tunnel_arch.png"; height: 100 width: 100 } Text { anchors.centerIn: parent; id:chosenItemText x: 11 y: 5 color: "#ffffff" text:"ENG"
; anchors.topMargin: 5 anchors.left: parent.left anchors.leftMargin: 12 font.family: "Arial" font.pointSize: 30; smooth:true visible: false; } MouseArea { width: 400 height: 30 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: 2; color: "red" ListView { id:listView height:500; model: comboBox.items currentIndex: 0; delegate: Item{ width:comboBox.width; height: comboBox.height; Image { id: img3; source: modelData.img; fillMode: Image.PreserveAspectFit anchors.fill: parent } Text { text: modelData.lang anchors.top: parent.top; anchors.left: parent.left; anchors.margins: 5; color: "#ffffff"; } MouseArea { anchors.fill: parent; onClicked: { comboBox.state = "" chosenItemText.text = modelData.lang; listView.currentIndex = index; main_img.source = comboBox.items[index].img } } } } } states: State { name: "dropDown"; PropertyChanges { target: dropDown; height:60*comboBox.items.length } } transitions: Transition { NumberAnimation { target: dropDown; properties: "height"; easing.type: Easing.OutExpo; duration: 1000 } } }

效果如下:
這裡寫圖片描述