2

I want to create a new shapefile (vector layer) from selected features. I select one feature then save that feature to a new shapefile.

When I use following code, I got a new shapefile but it's blank (blank attribute table, only field names available in the table). I want row entries based on the feature which is selected.

      filename = 'C:/temp/outputs/select_001.shp'
      selectedLayer = self.dlg.comboBox.currentLayer()
      selectedField = self.dlg.comboBox_2.currentField()
      selectedFeature = self.dlg.comboBox_3.currentText()
      selectedLayer.selectByExpression( "\"FIELD\"='{}' = \"FEAT\"='{}'".format( selectedField, selectedFeature ))
      #selection = layer.getFeatures(request)
      writer = QgsVectorFileWriter.writeAsVectorFormat(selectedLayer, filename, 'utf-8', driverName='ESRI Shapefile', onlySelected=True)
      selected_layer = self.iface.addVectorLayer(filename, '', 'ogr')
      del(writer)
1
  • Check if your filter selects anything
    – Ian Turton
    Jul 12, 2022 at 11:25

1 Answer 1

2

Your expression is wrong. You shouldn't have the strings "FIELD" or "FEAT" in your expression. What you are trying to check is "Field_name" LIKE 'Some string', and inserting your actual selected field name and selected value. Alternatively, you could use something like:

selectedLayer.selectByIds([f.id() for f in selectedLayer.getFeatures() if str(f[selectedField]) == selectedFeature])

Which should work for both text and numeric fields but may be slower on large datasets.

Also QgsVectorFileWriter.writeAsVectorFormat is deprecated for a while now. Use QgsVectorFileWriter.writeAsVectorFormatV2 instead (and after 3.20 this is also deprecated for writeAsVectorFormatV3). Try this (* don't forget to add QgsProject to your imports!):

    filename = 'C:/temp/outputs/select_001.shp'
    selectedLayer = self.dlg.comboBox.currentLayer()
    selectedField = self.dlg.comboBox_2.currentField()
    selectedFeature = self.dlg.comboBox_3.currentText()
    selectedLayer.selectByExpression( '"{}" LIKE \'{}\''.format( selectedField, selectedFeature ))
    # Or:
    #selectedLayer.selectByIds([f.id() for f in selectedLayer.getFeatures() if str(f[selectedField]) == selectedFeature])
    save_options = QgsVectorFileWriter.SaveVectorOptions()
    save_options.driverName = 'ESRI Shapefile'
    save_options.onlySelectedFeatures = True
    err, result = QgsVectorFileWriter.writeAsVectorFormatV2(selectedLayer, filename, QgsProject.instance().transformContext(), save_options)
    selectedLayer.removeSelection()
    if err == 0:
        self.iface.addVectorLayer(filename, '', 'ogr')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.