How do I perform a multiple search in the QML Listview.
I have the following piece of code and it works fine for single Listview element:
Page
{
ColumnLayout {
anchors.fill: parent
anchors.margins: 10
Label { text: qsTr("Search") }
Frame {
Layout.fillWidth: true
TextEdit {
id: searchTextEdit
width: parent.width
}
}
Label { text: qsTr("States (count:%1)").arg(filterDelegateModel.count) }
ListView {
Layout.fillWidth: true
Layout.fillHeight: true
clip: true
model: FilterDelegateModel {
id: filterDelegateModel
model: states
filter: search ? model => model.state.toLowerCase().indexOf(search) !== -1 : null
property string search: searchTextEdit.text.toLowerCase()
onSearchChanged: Qt.callLater(update)
delegate: Frame {
id: frame
property int visibleIndex: DelegateModel.visibleIndex
width: ListView.view.width
background: Rectangle {
color: visibleIndex & 1 ? "#e0e0e0" : "#d0d0d0"
border.color: "#c0c0c0"
}
RowLayout {
width: parent.width
Text {
text: (visibleIndex + 1)
color: "grey"
}
Text {
Layout.fillWidth: true
text: model.state
}
}
}
}
}
}
ListModel {
id: states
ListElement { state:"Durban" }
ListElement { state:"New York" }
ListElement { state:"Toronto" }
ListElement { state:"Mbabane" }
ListElement { state:"Harare" }
}
}
Now I’ve added a second property "Country" as follows and the search filter isn’t working anymore:
ListModel {
id: states
ListElement { state:"Durban"; country: "RSA" }
ListElement { state:"New York"; country: "USA" }
ListElement { state:"Toronto"; country: "Canada" }
ListElement { state:"Mbabane"; country: "Swaziland" }
ListElement { state:"Harare"; country: "Zimbabwe" }
}
I need to be able to filter the list by either the state or country.
2
Answers
Try updating your
FilterDelegateModel
filter function to search for the input text within both "state" and "country" properties. Here’s the modified code:This updated code enhances the filter function to consider both the "state" and "country" properties. As a result, your ListView will now filter items based on input text entered into the TextEdit, considering both the state and country properties of each item in the model.
You can join the strings together prior to doing an indexOf, e.g.
Here’s a full working example: