I have a QTableWidget which contains the names of layers and values. The code below creates a range of values from a list, iterates through some groups whilst creating a dictionary containing the layer name and value from the QTableWidget.
The output is a simple SQL expression which contains the layer name and its value in order of when the layer appears in the table. I want to change this order so that the layer with the higher values are included first.
Here is the code I used:
def func(self):
root = QgsProject.instance().layerTreeRoot()
group_name = root.findGroup('Group')
qTable = self.dockwidget.tableWidget
delim = ' WHEN '
# Number of layers in 5 groups
layer_count = [15, 14, 1, 2, 1]
top = list(np.cumsum(layer_count))
bottom = list(np.subtract(np.cumsum(layer_count),layer_count))
pairs = zip(bottom,top)
ranges = iter([range(x[0], x[1]) for x in pairs])
# Iterate through the 5 groups
for group in group_name.children():
value_dict = {}
for row in next(ranges):
first_item = qTable.item(row, 0)
first_name = str(first_item.text())
second_item = qTable.item(row,1)
value = str(second_item.text())
value_dict[first_name] = value
layers = [g.layerName() for g in group.children()]
fscorestrs = {k:delim.join('"{layer}_Score" = {N} THEN "{layer}_Score"'.format(
layer = l, N = value_dict[first_name]) for l in layers) for k in range(1)}
formula = ("CASE WHEN " + fscorestrs[0] + " ELSE NULL END")
For example:
Here is a simple layout for the QTableWidget:
If I use the above code, the formula reads:
CASE
WHEN "Layer_1_Score" = 0.1 THEN "Layer_1_Score"
WHEN "Layer_2_Score" = 0.7 THEN "Layer_2_Score"
WHEN "Layer_3_Score" = 0.5 THEN "Layer_3_Score"
WHEN "Layer_4_Score" = 0.8 THEN "Layer_4_Score"
WHEN "Layer_5_Score" = 0.6 THEN "Layer_5_Score"
ELSE NULL
END
What I am looking for is to instead produce an output where the layers are ordered in terms of the value, so the above should look like:
CASE
WHEN "Layer_4_Score" = 0.8 THEN "Layer_4_Score"
WHEN "Layer_2_Score" = 0.7 THEN "Layer_2_Score"
WHEN "Layer_5_Score" = 0.6 THEN "Layer_5_Score"
WHEN "Layer_3_Score" = 0.5 THEN "Layer_3_Score"
WHEN "Layer_1_Score" = 0.1 THEN "Layer_1_Score"
ELSE NULL
END
How could I achieve this?