示例#1
0
def load_layers(uris_and_names: List[Tuple[str,str,Optional[str]]], group_name=None,
                visible: Union[bool,int]=0, expanded: bool=True) -> List[QgsRasterLayer]:
    registry = QgsProject.instance() # type: QgsProject
    root = registry.layerTreeRoot() # type: QgsLayerTree
    if group_name:
        group = root.findGroup(group_name) # type: QgsLayerTreeGroup
        if group is None:
            group = root.insertGroup(0, group_name)
            group.setExpanded(expanded)
            visibility = (type(visible) == bool and visible) or (type(visible) == int)
            group.setItemVisibilityChecked(visibility)
        else:
            group.removeAllChildren()
    layers = []
    for i, (uri, name, short_name) in enumerate(uris_and_names):
        layer = QgsRasterLayer(uri, name)
        
        if short_name:
            layer.setShortName(short_name)
        fix_style(layer)
        registry.addMapLayer(layer, False)
        if group_name:
            layer_node = group.addLayer(layer) # type: QgsLayerTreeLayer
            visibility = (type(visible) == bool) or (type(visible) == int and i == visible)
        else:
            layer_node = root.insertLayer(0, layer)
            visibility = (type(visible) == bool and visible) or (type(visible) == int and i == visible)
        layer_node.setItemVisibilityChecked(visibility)
        layers.append(layer)

    return layers
示例#2
0
def add_raster_layer(MAP, url, name, shortname, is_basemap, provider='wms'):
    """Add a raster layer to the project,
    path: path of the project, relative to the projects' directory

    Return: id of the added layer
    """

    layer = QgsRasterLayer(url, name, 'wms')
    layer.setShortName(shortname)

    project = QgsProject()
    project.read(MAP)

    project = QgsProject.instance()

    add_to_legend = not is_basemap
    added_layer = project.addMapLayer(layer, addToLegend=add_to_legend)

    project.write()
    return added_layer.id()