5

I would like to create a model point dataset in QGIS 3.0.3 with Python in the QGIS Python Console to do some testing. Specifically, I want to create a point dataset that has a feature with an empty geometry, and, another feature with a NULL geometry.

What I have tried is:

layer = QgsVectorLayer('Point?crs=epsg:4326&field=id:string&field=type:string','ModelPoints',"memory")
pr = layer.dataProvider()

points = {}
points['Pt1'] = ['(1,1)', QgsPointXY(1,1)]
points['Pt2'] = ['(2,1)', QgsPointXY(1,1)]
points['Pt3'] = ['(4,1)', QgsPointXY(1,1)]
points['Pt4'] = ['empty', QgsPointXY()]
points['Pt5'] = ['null', None]

for id, point in points.items():
    pt = QgsFeature()   
    pt.setAttributes([id,point[0]])
    if point[1] is not None:
        pt.setGeometry(QgsGeometry.fromPointXY(point[1]))
    print(pt.geometry().asWkt())    
    pr.addFeature(pt)

layer.updateExtents()
QgsProject.instance().addMapLayer(layer)

In this code, the empty point geometry is intended to be created by:

pt.setGeometry(QgsGeometry.fromPointXY(QgsPointXY())

However, the result is:

pt.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(0,0))

So, my code is making a point with the vertex (0,0), but, whereas I need a point (or a geometry) with no vertices.

The approaches g = QgsGeometry.fromWkt('POINT') and g = QgsGeometry.fromWkt('POINT EMPTY') both result in a NULL geometry as shown by using print(g.isNull()).

1
  • 1
    I guess that QGIS has methods for handling WKT so you could have a try with WKT POINT EMPTY.
    – user30184
    Jun 7, 2018 at 6:07

3 Answers 3

4

One approach to creating an empty geometry is:

QgsGeometry.fromWkt('LineString()')

These can be tested by:

QgsGeometry.fromWkt('LineString()').isEmpty() # True
QgsGeometry.fromWkt('LineString()').isNull() # False

However, for an empty point, QGIS is currently displaying:

QgsGeometry.fromWkt('Point()').isNull() # True

So, empty line data sets can be constructed, but, there maybe an error for empty point datasets.

1

Sorry, if it's obvious, but you can simply create an instance of QgsGeometry without arguments.

For example

geom = QgsGeometry()
print(geom.isNull()) #True
print(geom.isEmpty()) #True
     
0

This creates a generic null geometry:

QgsGeometry().fromWkt('')

Qgis 3.10.5

1
  • 2
    but causes issues with the whole layer
    – MrXsquared
    Aug 31, 2020 at 19:11

Your Answer

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

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