01-27-2013 08:17 PM
Hi all,
I've been having some problems implementing sorting in my list.
I have a drop down with some sorting options. I can sort all the names in my json file well, but can't sort the numbers (in my sample json file below, sortP and sortA).
Is it something to do with the numbers being string? I've tried putting the numbers without quotes, and that seems to fix the problem.
BUT, my full list has about 500 numbers and changing them would be difficult. Any idea on how this can be fixed?
[
{
"name": "jamie",
"sortP": "100",
"sortA": "5"
},
{
"name": "linda",
"sortP": "400",
"sortA": "10"
},
{
"name": "richard",
"sortPopulation": "200",
"sortA": "80"
},
{
"name": "george",
"sortPopulation": "600",
"sortA": "19"
}
]
Here is some some code I'm using:
DropDown {
horizontalAlignment: HorizontalAlignment.Center
id: sortDropDown
title: "Sort"
enabled: true
onSelectedIndexChanged: {
sortIndex = selectedIndex;
}
Option {
text: "Name"
selected: true
}
Option {
text: "P"
}
Option {
text: "A"
}
}
Button {
id: ascendButton
text: "▲"
onClicked: {
sortContainer.visible = false;
sortCriteria = getSortString(sortIndex)
dataModel.sortingKeys = [
sortCriteria
]
dataModel.sortedAscending = true
}
}
Button {
id: descendButton
text: "▼"
onClicked: {
sortContainer.visible = false;
sortCriteria = getSortString(sortIndex)
dataModel.sortingKeys = [
sortCriteria
]
dataModel.sortedAscending = false
}
}
In case you want the "getSortString" function:
function getSortString(index) {
var result = "";
if (index == 0) {
result = "name"
}
if (index == 1) {
result = "sortP"
}
if (index == 2) {
result = "sortA"
}
return result
}
01-27-2013 08:37 PM
01-27-2013 09:34 PM
The strings in the JSON you mean?
I created my entire database in excel, saved it as a csv and converted it from csv to json using an online converter. It was just easy to compile all of it.
I'm loading the JSON in QML using the following way. These attached objects are attached to the container, which contains the ListView which displays the JSON contents.
attachedObjects: [
GroupDataModel {
id: dataModel
sortingKeys: [
"name"
]
grouping: ItemGrouping.None
sortedAscending: true
},
DataSource {
id: dataSource
source: "testNames.json"
onDataLoaded: {
dataModel.insertList(data);
}
}
]
I wouldn't mind storing that as integers. But would you know how to change this data quickly, rather than manually going through? I would want it to be future proof, in case updates are made.
Thanks!
G
01-29-2013 12:44 AM
Well, this happens because your "sortP" and "sortA" are not compared as numbers, but strings. And, since ASCII comparison takes place, "10" is less than "5" here. This causes the anomaly in your sort results.
As the Datasource class loads data from your JSON file as QVariant &data, i believe you wont be able to make any sort of string to integer conversions here. Hence, i feel the only way you could get this to work is to get "sortP" and "sortA" as numerals in the JSON file.
- DIshooom