TransWikia.com

geometry less memory layer in QGIS

Geographic Information Systems Asked on October 4, 2021

I’m writing a QGIS plugin and I need to create a table with some attributes that, in a second moment, I’ll load in a SpatiaLite database.

The table is created as a memory layer, but as I said, it is just a attribute table, so the features don’t have any geometric requirements.

I’m not able to create a memory layer without geometry. Is there a way to do that?

From the cookbook it seems it is not possible to create a geometryless memory layer.

I thought it was possible to set the geometry after the layer creation using a combination of QgsGeometry and from Wkb with a specific option activated.

But I’have not been able to do that.

Someone has some suggestions?

2 Answers

From QGIS 2.14 there is a very simple and straightforward way to to that. Just write None as the typical geometry:

layer = QgsVectorLayer('None', 'table_name', 'memory')
QgsMapLayerRegistry.instance().addMapLayer(layer) 

(In later versions of QGIS replace last line with:

QgsProject.instance().addMapLayer(layer)

)

hope this can help other users

Correct answer by matteo on October 4, 2021

I haven't really worked with plugins so not sure this solution would apply in your situation but I use the following code to create a geometry-less polygon memory layer:

from PyQt4.QtCore import *

# Create memory layer
layer = QgsVectorLayer("Polygon?crs=epsg:4326", "Table", "memory")
QgsMapLayerRegistry.instance().addMapLayer(layer)

# Begin editing memory layer and create 3 fields
layer.startEditing()
provider = layer.dataProvider()
provider.addAttributes([QgsField("Name", QVariant.String),QgsField("Area", QVariant.Int),QgsField("Size", QVariant.Double)])
layer.updateFields()

# Add a feature with attributes (and without geometry) to populate the 3 fields
attr = layer.dataProvider()
feat = QgsFeature()
feat.setAttributes(["UK", 151, 33.33])
attr.addFeatures([feat])

layer.commitChanges()

Answered by Joseph on October 4, 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