I have a vector layer (PostGIS) with line geometries. Some of these geometries have a length of 0.0, but they have two points with the same coordinate. I want to handle this features within a python script and tried to fetch all of them inside a polygon. When I use a QgsFeatureRequest,
feats = layer.getFeatures(QgsFeatureRequest().setFilterRect(myPolygon.boundingBox()))
the result contains only features with a length > 0.0, but not "zero-length-lines". How can I fetch these lines, too?
In the QGIS application I can see those "zero-length-lines"and I can select them manually. I checked this with a small script:
layer = iface.activeLayer()
fs = layer.selectedFeatures()
for f in fs:
g = f.geometry()
print("WKB type",g.type())
if g.type() == QgsWkbTypes.LineGeometry:
print("LineGeom")
print("length: ", g.length())
It returns for the selected features:
WKB type 1
LineGeom
length: 0.0 <----
WKB type 1
LineGeom
length: 2.996556190491762
1 Answer 1
To also get invalid geometries you can try to set the QgsFeatureRequest()
to GeometryNoCheck
actively:
# just get some test features...
lines = QgsProject.instance().mapLayersByName('lines')[0]
polygons = QgsProject.instance().mapLayersByName('polygon')[0]
mypolygon = polygons.getFeature(1)
# setup the QgsFeatureRequest():
req = QgsFeatureRequest()
req.setFilterRect(mypolygon.geometry().boundingBox())
req.setInvalidGeometryCheck(QgsFeatureRequest.GeometryNoCheck)
# get the features and iterate over them, it should also print length 0 of the invalid ones
linefeatures = lines.getFeatures(req)
for linefeature in linefeatures:
print(linefeature.geometry().length())
Other attributes than GeometryNoCheck
would be GeometryAbortOnInvalid
or GeometrySkipInvalid
, see https://qgis.org/pyqgis/3.0/core/Feature/QgsFeatureRequest.html. I guess you may have set GeometrySkipInvalid
as default in your settings or something like that.
feats = layer.getFeatures(QgsFeatureRequest().setFilterRect(QgsRectangle(-1, -1, 2, 2)))
gets both of them. Are you sure yourmypolygon
contains everything?select ST_IsValid('LINESTRING(1 1, 1 1)')
returns "false". Would you like to find them for fixing the geometries or why?