Monday, March 19, 2012

QML Drop Down Menu

A drop down menu example. There are two states of the drop down list - dropDown and, well, not dropDown. When the top rectangle (chosenItem) is clicked, the state is switched from dropDown to none and back, and the height of the dropdownList is adjusted accordingly, showing or hiding the list with the selection options. When the list itself is clicked, there is an additional action - the text of the chosenItemText area is updated to reflect the selection.

List is expanded

A selection was made, text is updated and list is hidden again

import QtQuick 1.0

Rectangle {
width:400;
height: 400;

property int dropDownHeight:40

Rectangle {
id:dropdown
property variant items: ["Test Item 1", "Test Item 2", "Test Item 3"]
width: 100;
height: dropDownHeight;
z: 100;

Rectangle {
id:chosenItem
width:parent.width;
height:dropdown.height;
color: "lightsteelblue"
Text {
anchors.top: parent.top;
anchors.left: parent.left;
anchors.margins: dropDownHeight/5;
id:chosenItemText
text:dropdown.items[0];
}

MouseArea {
anchors.fill: parent;
onClicked: {
dropdown.state = dropdown.state==="dropDown"?"":"dropDown"
}
}
}

Rectangle {
id:dropdownList
width:dropdown.width;
height:0;
clip:true;
anchors.top: chosenItem.bottom;
anchors.margins: 2;
color: "lightgray"

ListView {
id:listView
height:dropDownHeight*dropdown.items.length
model: dropdown.items
currentIndex: 0
delegate: Item{

width:dropdown.width;
height: dropdown.height;

Text {
text: modelData
anchors.top: parent.top;
anchors.left: parent.left;
anchors.margins: 5;
}

MouseArea {
anchors.fill: parent;
onClicked: {
dropdown.state = "";
chosenItemText.text = modelData;
listView.currentIndex = index;
}
}
}
}
}

states: State {
name: "dropDown";
PropertyChanges { target: dropdownList; height:dropDownHeight*dropdown.items.length }
}
}
}

References:

QML drop Down Menu or Menu bar
Qt QML dropdown list like in HTML
by . Also posted on my website

No comments: