From 28382e1f12dec996e5cbab18425c5448b8ff94a4 Mon Sep 17 00:00:00 2001 From: luca from muntzer Date: Fri, 12 Feb 2021 11:23:39 +0100 Subject: [PATCH] forgot files 2 --- qgis_plugin/qgismappy/utils.py | 55 ++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 qgis_plugin/qgismappy/utils.py diff --git a/qgis_plugin/qgismappy/utils.py b/qgis_plugin/qgismappy/utils.py new file mode 100644 index 0000000..b70afd0 --- /dev/null +++ b/qgis_plugin/qgismappy/utils.py @@ -0,0 +1,55 @@ +from qgis.PyQt.QtCore import NULL +from qgis.core import QgsCategorizedSymbolRenderer, QgsSymbol, QgsRendererCategory + + +def resetCategoriesIfNeeded(layer, units_field, unassigned=True): + prev_rend = layer.renderer() + + if not isinstance(prev_rend, QgsCategorizedSymbolRenderer): + renderer = QgsCategorizedSymbolRenderer(units_field) + layer.setRenderer(renderer) + else: + renderer = prev_rend + + prev_cats = renderer.categories() + id = layer.fields().indexFromName(units_field) + uniques = list(layer.uniqueValues(id)) + uniques_clean = [] + + for u in uniques: + if u not in [None, NULL]: + uniques_clean.append(u) + + values = sorted(uniques_clean) + + if unassigned: + if None in uniques or NULL in uniques: + values.append("") + + categories = [] + + for current, value in enumerate(values): + + already_in = False + for prev in prev_cats: + if prev.value() == value: + already_in = True + continue + + if not already_in: + if value =="": + name = "Unassigned" + else: + name = str(value) + symbol = QgsSymbol.defaultSymbol(layer.geometryType()) + category = QgsRendererCategory(value, symbol, name) + categories.append(category) + + for cat in categories: + renderer.addCategory(cat) + + # layer.setRenderer(renderer) + layer.rendererChanged.emit() + layer.dataSourceChanged.emit() + + layer.triggerRepaint() \ No newline at end of file