Use Delegate in ComboBox
Unsolved
QML and Qt Quick
-
Hi, I very new in Qt, now I need to use delegate to populate items in a ComboBox, I can find that Text can be used to assign text of a item, but I do not know how to apply item's value. it is like only textRole works, but I do not know how to make valueRole work in delegate.
My code look like this, it loads items for now.
ComboBox { implicitWidth: 150 editable: false ToolTip.text: qsTr('Select Item') ToolTip.visible: hovered model: itemsModel currentIndex: indexOfValue(getPropertyInt("items")) delegate:ItemDelegate{ required property var properties id: itemInfo text: itemInfo.properties.name } } }
-
@chiyuwang Your model should provide a role name for the desired value, let's say
value
, then you can inform the combobox via itsvalueRole
property.
See the example below, copied from Qt documentationApplicationWindow { width: 640 height: 480 visible: true // Used as an example of a backend - this would usually be // e.g. a C++ type exposed to QML. QtObject { id: backend property int modifier } ComboBox { textRole: "text" valueRole: "value" // When an item is selected, update the backend. onActivated: backend.modifier = currentValue // Set the initial currentIndex to the value stored in the backend. Component.onCompleted: currentIndex = indexOfValue(backend.modifier) model: [ { value: Qt.NoModifier, text: qsTr("No modifier") }, { value: Qt.ShiftModifier, text: qsTr("Shift") }, { value: Qt.ControlModifier, text: qsTr("Control") } ] } }