Shapefile output¶
Note
The code can be downloaded from https://github.com/GISMentors/yungo-plugins/tree/master/src/fiberplanitconvert-03-qgis-shp
ESRI Shapefile is one of the most common (file-based) GIS formats.
For writing the data into Esri Shapefile, there are 2 possible options:
Creating Shapefile from scratch¶
The QgsVectorFileWriter class enables to create a new file-based layer.
fields = QgsFields()
fields.append(QgsField("attr1", QVariant.String))
fields.append(QgsField("attr2", QVariant.Int))
file = QgsVectorFileWriter(
"/tmp/out.shp",
"UTF8",
fields,
QgsWkbTypes.Point,
QgsCoordinateReferenceSystem(4326),
"ESRI Shapefile"
)
layer = QgsVectorLayer("/tmp/out.gpkg", "baf", "ogr")
QgsProject.instance().addMapLayer(layer)
feature = QgsFeature()
feature.setFields(layer.fields())
feature.setGeometry(QgsGeometry().fromWkt("Point(0 0)"))
feature.setAttribute("attr1", "attttr")
feature.setAttribute("attr2", 2)
layer.startEditing()
layer.addFeature(feature)
layer.commitChanges()
The idea of the code is to approach step-by-step
- A set of attributes is defined by QgsFields and QgsField classes
- New file with geometry, attributes and other metadata is created
- The file is loaded to QGIS project using the ogr driver
- New vector feature QgsFeature is created and attribute fields are set
- Geometry is read from the WKT format, attributes are assigned directly
- Feature is added to the layer
Creating Shapefile from memory layer¶
QGIS has possibility to copy features from one layer to another one using writeAsVectorFormat method of the QgsVectorFileWriter class
QgsVectorFileWriter.writeAsVectorFormat(
new_layer, output_file, "utf-8", driverName="ESRI Shapefile")
Qt Designer¶
We need to define 4th user input: name for the new to-be-created Shapefile
Úkol
In the Qt Designer add QgsFileWidget and use objectName attribute to name it accordingly.
You also have to mark the dialogue mode with QgsFileWidget.SaveFile later in the code.
The Code¶
Related modifications will be relatively simple.
- We have to mark the input for the new Shapefile for saving.
- We have to write features from the memory layer to the new Shapefile and add the new file to list of layers of currently running project.
Úkol
Try to add new layer by yourselves.