Ejemplo n.º 1
0
    def Changed(self, item):
        # if item has been changed in coordinate table
        # editing mode is required
        # print self.coord_tab.currentColumn()
        # print self.coord_tab.currentRow()
        if self.v_points.isEditable():
            # print self.coord_tab.currentItem()
            # print self.coord_tab.currentColumn()
            # print self.coord_tab.currentRow()
            # coordinate which has been edited (only one at a time)
            coord_edit = float(self.coord_tab.currentItem().text())

            # change coordinate equals "coord_edit"
            if self.coord_tab.currentColumn() == 1:
                x = coord_edit
                y = float(self.coord_tab.item(self.rows[0], 2).text())

            elif self.coord_tab.currentColumn() == 2:
                x = float(self.coord_tab.item(self.rows[0], 1).text())
                y = coord_edit

            # QGIS internal functions
            # move vertex to new coordinates
            ch = QgsVectorLayerEditUtils(self.v_points)
            ch.moveVertex(x, y, self.rows[0], 0)
Ejemplo n.º 2
0
    def move_link_vertex(params, link_lay, link_ft, new_pos_pt_v2, vertex_index):
        caps = link_lay.dataProvider().capabilities()

        if caps & QgsVectorDataProvider.ChangeGeometries:
            link_lay.beginEditCommand("Update pipes geometry")

            try:
                edit_utils = QgsVectorLayerEditUtils(link_lay)
                edit_utils.moveVertexV2(new_pos_pt_v2, link_ft.id(), vertex_index)
                # Retrieve the feature again, and update attributes

                if link_lay == params.pipes_vlay:

                    request = QgsFeatureRequest().setFilterFid(link_ft.id())
                    feats = list(link_lay.getFeatures(request))

                    field_index = link_lay.dataProvider().fieldNameIndex(Pipe.field_name_length)
                    new_3d_length = LinkHandler.calc_3d_length(params, feats[0].geometry())
                    link_lay.changeAttributeValue(link_ft.id(), field_index, new_3d_length)

            except Exception as e:
                link_lay.destroyEditCommand()
                raise e

            link_lay.endEditCommand()
Ejemplo n.º 3
0
    def move_element(layer, dem_rlay, node_ft, new_pos_pt):
        caps = layer.dataProvider().capabilities()

        if caps & QgsVectorDataProvider.ChangeGeometries:

            layer.beginEditCommand('Move node')

            try:

                edit_utils = QgsVectorLayerEditUtils(layer)

                edit_utils.moveVertex(
                    new_pos_pt.x(),
                    new_pos_pt.y(),
                    node_ft.id(),
                    0)

                # Elevation
                new_elev = raster_utils.read_layer_val_from_coord(dem_rlay, new_pos_pt, 1)
                if new_elev is None:
                    new_elev = 0

                field_index = layer.dataProvider().fieldNameIndex(Junction.field_name_elev)
                layer.changeAttributeValue(node_ft.id(), field_index, new_elev)

            except Exception as e:

                layer.destroyEditCommand()
                raise e

            layer.endEditCommand()
Ejemplo n.º 4
0
    def add_topological_vertices(self, layer1, layer2, id_field=ID_FIELD):
        """
        Modify layer1 adding vertices that are in layer2 and not in layer1

        Ideally, we could pass the whole layer2 as parameter for
        addTopologicalPoints or, at least, pass one multi-geometry containing
        all geometries from layer2. However, onthe one side, the
        addTopologicalPoints function doesn't support a layer as parameter and,
        on the other side, there is a bug in the function that doesn't let it
        work with multi-geometries. That's why we need to traverse the whole
        layer2 in search for its individual geometries. We do use a SpatialIndex
        nonetheless, to improve efficiency.
        """
        if QgsWkbTypes.isMultiType(layer2.wkbType()):
            layer2 = processing.run("native:multiparttosingleparts", {
                'INPUT': layer2,
                'OUTPUT': 'memory:'
            })['OUTPUT']

        if layer2.geometryType() == QgsWkbTypes.PolygonGeometry:
            layer2 = processing.run("ladm_col:polygonstolines", {
                'INPUT': layer2,
                'OUTPUT': 'memory:'
            })['OUTPUT']

        geom_added = list()
        index = QgsSpatialIndex(layer2)
        dict_features_layer2 = None
        candidate_features = None
        id_field_idx1 = layer1.fields().indexFromName(id_field)
        request1 = QgsFeatureRequest().setSubsetOfAttributes([id_field_idx1])
        id_field_idx2 = layer2.fields().indexFromName(id_field)
        request2 = QgsFeatureRequest().setSubsetOfAttributes([id_field_idx2])

        with edit(layer1):
            edit_layer = QgsVectorLayerEditUtils(layer1)
            dict_features_layer2 = {
                feature.id(): feature
                for feature in layer2.getFeatures(request2)
            }

            for feature in layer1.getFeatures(request1):
                bbox = feature.geometry().boundingBox()
                candidate_ids = index.intersects(bbox)
                candidate_features = [
                    dict_features_layer2[candidate_id]
                    for candidate_id in candidate_ids
                ]

                for candidate_feature in candidate_features:
                    if candidate_feature.id() not in geom_added:
                        edit_layer.addTopologicalPoints(
                            candidate_feature.geometry())
                        geom_added.append(candidate_feature.id())

        # free up memory
        del candidate_features
        del dict_features_layer2
        gc.collect()
Ejemplo n.º 5
0
 def deleteVertexLink(self, layer, feature, vertexIndex):
     if layer.isEditable():
         layer.beginEditCommand("Update link geometry")
         try:
             edit_utils = QgsVectorLayerEditUtils(layer)
             edit_utils.deleteVertex(feature.id(), vertexIndex)
         except Exception as e:
             layer.destroyEditCommand()
             raise e
         layer.endEditCommand()
Ejemplo n.º 6
0
 def moveNodePoint(self, layer, nodeFeature, newPosition):
     if layer.isEditable():
         layer.beginEditCommand('Move node')
         try:
             edit_utils = QgsVectorLayerEditUtils(layer)
             edit_utils.moveVertex(newPosition.x(), newPosition.y(),
                                   nodeFeature.id(), 0)
         except Exception as e:
             layer.destroyEditCommand()
             raise e
         layer.endEditCommand()
    def addTopologicalPointsForActiveLayers(self, geometry):
        geometry = QgsGeometry(geometry)
        layers = self.getVisibleLayers()
        for layer in layers:
            if not layer.isEditable():
                layer.startEditing()

            topology = QgsVectorLayerEditUtils(layer)
            vertices = [v for v in geometry.vertices()]

            for v in vertices:
                point = v.asWkt()
                point = QgsGeometry.fromWkt(point)
                point = point.asPoint()
                topology.addTopologicalPoints(point)  
            
        return True
Ejemplo n.º 8
0
    def addTopologicalPoints(self, geometry):
        geometry = QgsGeometry(geometry)
        layers = self.getLayers(2)

        for l in layers:
            layer = l[0]
            if not layer.isEditable():
                layer.startEditing()

            topology = QgsVectorLayerEditUtils(layer)
            vertices = [v for v in geometry.vertices()]

            for v in vertices:
                point = v.asWkt()
                point = QgsGeometry.fromWkt(point)
                point = point.asPoint()
                topology.addTopologicalPoints(point)  
Ejemplo n.º 9
0
 def insertVertexLink(self, layer, feature, newPoint):
     if layer.isEditable():
         layer.beginEditCommand("Update link geometry")
         vertex = -1
         if layer.geometryType() == 1:  # Line
             featureGeometry = self.selectedFeature.geometry()
             if featureGeometry.isMultipart():
                 parts = featureGeometry.get()
                 for part in parts:  # only one part
                     for i in range(len(part)-1):
                         if self.isInPath(QgsPointXY(part[i].x(), part[i].y()),
                                          QgsPointXY(part[i+1].x(), part[i+1].y()), newPoint):
                             vertex = i+1
         try:
             edit_utils = QgsVectorLayerEditUtils(layer)
             edit_utils.insertVertex(
                 newPoint.x(), newPoint.y(), feature.id(), vertex)
         except Exception as e:
             layer.destroyEditCommand()
             raise e
         layer.endEditCommand()
Ejemplo n.º 10
0
    def delete_vertex(params, layer, pipe_ft, vertex_index):
        caps = layer.dataProvider().capabilities()

        if caps & QgsVectorDataProvider.ChangeGeometries:
            layer.beginEditCommand("Update pipe geometry")

            # try:
            edit_utils = QgsVectorLayerEditUtils(params.pipes_vlay)
            edit_utils.deleteVertexV2(pipe_ft.id(), vertex_index)

            # Retrieve the feature again, and update attributes
            request = QgsFeatureRequest().setFilterFid(pipe_ft.id())
            feats = list(params.pipes_vlay.getFeatures(request))

            field_index = params.pipes_vlay.dataProvider().fieldNameIndex(Pipe.field_name_length)
            new_3d_length = LinkHandler.calc_3d_length(params, feats[0].geometry())
            params.pipes_vlay.changeAttributeValue(pipe_ft.id(), field_index, new_3d_length)

            # except Exception as e:
            #     params.pipes_vlay.destroyEditCommand()
            #     raise e

            params.pipes_vlay.endEditCommand()
Ejemplo n.º 11
0
    def move_pump_valve(vlay, feature, delta_vector):
        caps = vlay.dataProvider().capabilities()
        if caps and QgsVectorDataProvider.ChangeGeometries:
            vlay.beginEditCommand('Update pump/valve')
            try:

                old_ft_pts = feature.geometry().asPolyline()
                edit_utils = QgsVectorLayerEditUtils(vlay)

                edit_utils.moveVertex(
                    (QgsPoint(old_ft_pts[0].x() + delta_vector.x(), old_ft_pts[0].y() + delta_vector.y())).x(),
                    (QgsPoint(old_ft_pts[0].x() + delta_vector.x(), old_ft_pts[0].y() + delta_vector.y())).y(),
                    feature.id(),
                    0)
                # In 2.16
                # edit_utils.moveVertex(
                #     (old_ft_pts[0] + delta_vector).x(),
                #     (old_ft_pts[0] + delta_vector).y(),
                #     ft.id(),
                #     0)

                edit_utils.moveVertex(
                    (QgsPoint(old_ft_pts[1].x() + delta_vector.x(), old_ft_pts[1].y() + delta_vector.y())).x(),
                    (QgsPoint(old_ft_pts[1].x() + delta_vector.x(), old_ft_pts[1].y() + delta_vector.y())).y(),
                    feature.id(),
                    1)
                # In 2.16
                # edit_utils.moveVertex(
                #     (old_ft_pts[1] + delta_vector).x(),
                #     (old_ft_pts[1] + delta_vector).y(),
                #     ft.id(),
                #     1)

            except Exception as e:
                vlay.destroyEditCommand()
                raise e

            vlay.endEditCommand()
for i in infos:
    fet = QgsFeature()
    fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(i[0], i[1])))
    fet.setAttributes(i[2:5])
    pr.addFeatures([fet])

# update layer's extent when new features have been added
# because change of extent in provider is not propagated to the layer
vl.updateExtents()

QgsMapLayerRegistry.instance().addMapLayer(vl)

feat = vl.getFeatures().next()
canvas = iface.mapCanvas()

vector_layer_edit_utils = QgsVectorLayerEditUtils(vl)
vl.startEditing()
vector_layer_edit_utils.translateFeature(
    feat.id(),
    -5,  # dx
    1.0  # dy
)
vl.commitChanges()

# If caching is enabled, a simple canvas refresh might not be sufficient
# to trigger a redraw and you must clear the cached image for the layer
if canvas.isCachingEnabled():
    vl.setCacheImage(None)
else:
    canvas.refresh()