I have an XmlListModel in QML
XmlListModel {
id: model
source: "qrc:/Config/myConfig.xml"
query: "/levels/level"
XmlRole { name: "levName"; query: "@levName/string()" }
XmlRole { name: "from"; query: "from/number()" }
XmlRole { name: "to"; query: "to/number()" }
}
that reads this XML file
<levels parId = "3">
<level levelName = "level1">
<from>0</from>
<to>1</to
</level>
<level levelName = "level2">
<from>1</from>
<to>2</to>
</level>
</levels>
I also have a text element:
Text {
id: myText
x: 0; y:0
text: ""
}
I need to iterate through the XmlListModel
in order to assign to myText.text
the right level on the basis of what I found in myList.get(3).value
, where myList
is a ListModel
.
Example:
if myList.get(3).value
is between 0
(included) and 1
(excluded) I have to set myText.text = "level1"
, if it is between 1
(included) and 2
(excluded) I have to set myText.text = "level2"
, and so on...
Any suggestion?
Unfortunately you can't query your XmlListModel in O(1)
like give me the value, where x is between role from and role to
.
Good for you, you have an ordered list, so you can perform a binary search on your XmlListModel
. The algorithm basically goes like this:
You first check whether your search value is by coincidence the one in the middle. If it is smaller, you search in the middle of the lower half, if it is larger, you search in the upper half... and so on.
With this you can find your value in O(log n)
where n
is the number of entries in your XmlListModel
.
https://en.wikipedia.org/wiki/Binary_search_algorithm
If you have this implemented, to work on your model - either in JavaScript or in C++ or Python... you can have it like this:
Text {
text: binarySearch(model, myList.get(3).value).levName
}
When you implement this algorithm, make sure to deal with the gaps.