This repository has been archived by the owner on May 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
9f7cb8e
commit 28382e1
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() |