|
| 1 | +from dataclasses import dataclass |
| 2 | + |
| 3 | +from typing import List |
| 4 | + |
| 5 | +from qgis.core import QgsProject, QgsVectorLayer, QgsMapLayer |
| 6 | + |
| 7 | + |
| 8 | +@dataclass |
| 9 | +class LandUsePlan: |
| 10 | + id: str |
| 11 | + name: str |
| 12 | + |
| 13 | + |
| 14 | +LAYER_PLAN_ID_MAP = { |
| 15 | + "Kaava": "id", |
| 16 | + "Aluevaraus": "plan_id", |
| 17 | + "Osa-alue": "plan_id", |
| 18 | +} |
| 19 | + |
| 20 | + |
| 21 | +def update_selected_plan(new_plan: LandUsePlan): |
| 22 | + id = new_plan.id |
| 23 | + for layer_name, field_name in LAYER_PLAN_ID_MAP.items(): |
| 24 | + set_filter_for_layer(layer_name, field_name, id) |
| 25 | + |
| 26 | + |
| 27 | +def set_filter_for_layer(layer_name: str, field_name: str, field_value: str): |
| 28 | + # Get layer and perform checks |
| 29 | + layers = QgsProject.instance().mapLayersByName(layer_name) |
| 30 | + if not _check_layer_count(layers): |
| 31 | + return |
| 32 | + layer = layers[0] |
| 33 | + if not _check_vector_layer(layer): |
| 34 | + return |
| 35 | + |
| 36 | + # Perform the filtering |
| 37 | + query = f"{field_name} = {field_value}" |
| 38 | + if not layer.setSubsetString(query): |
| 39 | + # TODO: Convert to log msg? |
| 40 | + print(f"ERROR: Failed to filter layer {layer_name} with query {query}") |
| 41 | + |
| 42 | + |
| 43 | +def _check_layer_count(layers: List[QgsMapLayer]) -> bool: |
| 44 | + if len(layers) > 1: |
| 45 | + # TODO: Convert to log msg? |
| 46 | + print(f"ERROR: Found multiple layers ({len(layers)}) with same name ({layers[0].name()}).") |
| 47 | + return False |
| 48 | + return True |
| 49 | + |
| 50 | + |
| 51 | +def _check_vector_layer(layer: QgsMapLayer) -> bool: |
| 52 | + if not isinstance(layer, QgsVectorLayer): |
| 53 | + # TODO: Convert to log msg? |
| 54 | + print(f"ERROR: Layer {layer.name()} is not a vector layer: f{type(layer)}") |
| 55 | + return False |
| 56 | + return True |
0 commit comments