5

I need to change the position of a box only if it has a common attribute with a point. In my example if the feature "ID_PARENT" is the same as "CODE".

box = QgsProject.instance().mapLayersByName('box')[0]
point = QgsProject.instance().mapLayersByName('point')[0]

for bfeat in box.getFeatures():
    for pfeat in point.getFeatures():
        if bfeat['ID_PARENT'] == pfeat['CODE']:
            pfeat.geometry() = bfeat.geometry()

Here this code is totally false because I'm assigning a value to a function call but I think it illustrates well what I tried to do which is changing the WKT coordinate.

0

1 Answer 1

10

I guess you want to move a box' centroid position to another point if it has a common attribute with the point. I assume ID_PARENT and CODE are unique values. Use this script:

box_layer = QgsProject.instance().mapLayersByName('box')[0]
point_layer = QgsProject.instance().mapLayersByName('point')[0]

dpr = box_layer.dataProvider()

for box in box_layer.getFeatures():
    for point in point_layer.getFeatures():
        if box['ID_PARENT'] == point['CODE']:
            box_as_point = box.geometry().centroid().asPoint()
            point_as_point = point.geometry().centroid().asPoint()
            
            dx = point_as_point.x() - box_as_point.x()
            dy = point_as_point.y() - box_as_point.y()
            geom = box.geometry()
            geom.translate(dx, dy)
            
            dpr.changeGeometryValues({box.id(): geom})
            
            break

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.