Shapefile output

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

  1. A set of attributes is defined by QgsFields and QgsField classes
  2. New file with geometry, attributes and other metadata is created
  3. The file is loaded to QGIS project using the ogr driver
  4. New vector feature QgsFeature is created and attribute fields are set
  5. Geometry is read from the WKT format, attributes are assigned directly
  6. 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.

../_images/qt_designer_03.png

The Code

Related modifications will be relatively simple.

  1. We have to mark the input for the new Shapefile for saving.
  2. 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.