TransWikia.com

Missing results from ReshapeGeometry method on PyQGIS

Geographic Information Systems Asked by Val P on June 23, 2021

I am trying to use the method reshapeGeometry from QgsGeometry class in a script to reshape a feature geometry (polygon) according to a line.
The result of the process is 0, so positive, but I can’t see any change in my geometry.

This is an example of my script:

layer = iface.activeLayer()
line = QgsLineString([QgsPoint(1, 1), QgsPoint(2, 2)])

for feat in layer.selectedFeatures():
    c = feat.geometry().reshapeGeometry(line)
    print(c)
    

The feat in this script is a simple polygon with WKT.

Polygon ((1.16531548008501851 1.44378001491727948, 1.60296509683766097 1.93729979551068476, 2.06544589751953112 1.57103983255457269, 1.60296509683766097 1.0309615820938649, 1.16531548008501851 1.44378001491727948))
0

as observable in the image below (in green). The red line is the representation of the line used for the reshaping.

enter image description here

I have tried both to make the layer editable before and saving the edits after and to reload the layer after the operation.

I am working in the PyQGIS console on QGIS 3.16 and 3.19 dev.

One Answer

As I understand it, the only way to update geometry on the go (using this reshapeGeometry method at least) is to access the layer's data provider:

layer = iface.activeLayer()
provider = layer.dataProvider()
line = QgsLineString([QgsPoint(1, 1), QgsPoint(2, 2)])

feats_to_update=[]
for feat in layer.selectedFeatures():
    geom = feat.geometry()
    geom.reshapeGeometry(line)
    feats_to_update.append([feat.id(),geom])

provider.changeGeometryValues({
  feats_to_update[0]: feats_to_update[1] for feats_to_update in feats_to_update
})

layer.triggerRepaint()

enter image description here

However, one drawback is that (at least for me) this does not work on layers saved in memory, but only on files saved locally.

Correct answer by 15Step on June 23, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP