Criando polígono e adicionando-o como nova camada com PyQGIS

Sep 07 2020

Estou tentando adicionar um polígono a uma nova camada usando PyQGIS no QGIS 3.14. Adaptando alguns exemplos de perguntas e respostas aqui e aqui . Acredito ter criado com sucesso o polígono a partir de uma matriz de (quatro) pontos de entrada e, em seguida, um recurso que contém o polígono.

Em seguida, criei uma camada para o recurso no CRS que desejo, mas não consigo trabalhar como colocar o recurso na camada. Código até agora abaixo.

# Attach modules 
from qgis.core import *                        # attach main QGIS library
from qgis.utils import *                       # attach main python library
import os                                      # attach operating system library

# Create an array [] object with the polygon vertices
vrtcs = []
vrtcs.append(QgsPointXY(396100,8969000))
vrtcs.append(QgsPointXY(396100,8973900))
vrtcs.append(QgsPointXY(397900,8973900))
vrtcs.append(QgsPointXY(397900,8969000))

# Create a polygon from the coordinates
ply_01 = QgsGeometry.fromPolygonXY([vrtcs])

# Create a feature object then put the polygon into the feature
ftr = QgsFeature()
ftr.setGeometry(ply_01)
print(ftr.geometry())

# Create a layer for the feature, in the desired CRS
lyr = QgsVectorLayer('Polygon?crs=epsg:29194', '200905_Bdy',"org")
Prj.addMapLayers([lyr]) 

# Set an object for the data provider for the layer
prv = lyr.dataProvider()                               

# Add the feature to the layer using this provider (fails)
prv.addFeatures([ftr])

Respostas

3 KadirŞahbaz Sep 07 2020 at 10:34

Mude 'org'para 'memory'e adicione Prj = QgsProject.instance()linha antes de usar Prj.

...

# Create a layer for the feature, in the desired CRS
lyr = QgsVectorLayer('Polygon?crs=epsg:29194', '200905_Bdy', "memory")
Prj = QgsProject.instance()  # ADD THIS LINE
Prj.addMapLayers([lyr])

Como você adiciona uma camada, pode usar em Prj.addMapLayer(lyr)vez de Prj.addMapLayers([lyr]).

...
2 ComradeChe Sep 07 2020 at 06:05

Você deve começar a editar antes de adicionar o recurso à camada e confirmar as alterações depois de concluir:

if feature.isValid():
    layer.startEditing()
    layer.addFeatures([feature])
    commited = layer.commitChanges()
    if commited:
        return True
    else:
        print(f'{layer.commitErrors()}')
        return False