11"""Layer tree panel configuration"""
2- from __future__ import annotations
3-
42import contextlib
53import hashlib
64import json
108 TYPE_CHECKING ,
119 Any ,
1210 Protocol ,
11+ Tuple ,
1312)
1413
1514from qgis .core import (
@@ -883,7 +882,7 @@ def _add_group_legend(
883882 root_group = project .layerTreeRoot ()
884883
885884 qgis_group = self .existing_group (root_group , label )
886- if qgis_group :
885+ if qgis_group is not None :
887886 return qgis_group
888887
889888 new_group = root_group .addGroup (label )
@@ -892,16 +891,16 @@ def _add_group_legend(
892891 return new_group
893892
894893 @staticmethod
895- def existing_group (
896- root_group : QgsLayerTree ,
894+ def _existing_group (
895+ root_group : Optional [ QgsLayerTree ] ,
897896 label : str ,
898897 index : bool = False ,
899- ) -> QgsLayerTreeGroup | int | None :
898+ ) -> Optional [ Tuple [ QgsLayerTreeGroup , int ]] :
900899 """Return the existing group in the legend if existing.
901900
902901 It will either return the group itself if found, or its index.
903902 """
904- if not root_group :
903+ if root_group is None :
905904 return None
906905
907906 # Iterate over all child (layers and groups)
@@ -912,19 +911,34 @@ def existing_group(
912911 i += 1
913912 continue
914913
915- qgis_group = cast_to_group (child )
916- qgis_group : QgsLayerTreeGroup
914+ qgis_group : QgsLayerTreeGroup = cast_to_group (child )
917915 count_children = len (qgis_group .children ())
918916 if count_children >= 1 or qgis_group .name () == label :
919917 # We do not want to count empty groups
920918 # Except for the one we are looking for
921919 i += 1
922920
923921 if qgis_group .name () == label :
924- return i if index else qgis_group
922+ return ( qgis_group , i )
925923
926924 return None
927925
926+ @staticmethod
927+ def existing_group (
928+ root_group : Optional [QgsLayerTree ],
929+ label : str ,
930+ ) -> Optional [QgsLayerTreeGroup ]:
931+ g = LayerTreeManager ._existing_group (root_group , label )
932+ return g [0 ] if g is not None else None
933+
934+ @staticmethod
935+ def existing_group_index (
936+ root_group : Optional [QgsLayerTree ],
937+ label : str ,
938+ ) -> Optional [QgsLayerTreeGroup ]:
939+ g = LayerTreeManager ._existing_group (root_group , label )
940+ return g [1 ] if g is not None else None
941+
928942 def _add_base_layer (
929943 self ,
930944 source : str ,
0 commit comments