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()).

Taras
  • 32,823
  • 4
  • 66
  • 137
Philip Whitten
  • 997
  • 5
  • 21

3 Answers3

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.

Taras
  • 32,823
  • 4
  • 66
  • 137
Philip Whitten
  • 997
  • 5
  • 21
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

Taras
  • 32,823
  • 4
  • 66
  • 137
Luis Perez
  • 1,284
  • 4
  • 11
0

This creates a generic null geometry:

QgsGeometry().fromWkt('')

Qgis 3.10.5

cefect
  • 184
  • 1
  • 5