2

I would like to create a layer with a filter on one of my columns (GAMME_DE_S). I saw that I can use setSubsetString but no way to use it.

uri = r"C:\impression_plan\FicheCana.shp"
layer = QgsVectorLayer(uri, "", "ogr")
resultat_layer=layer

layer.setSubsetString("GAMME_DE_S=VSR")
9

Change

layer.setSubsetString("GAMME_DE_S=VSR")

to

layer.setSubsetString("GAMME_DE_S='VSR'")

Then to add the layer,

if not layer.isValid():
    print("Layer failed to load!")
else:
    QgsProject.instance().addMapLayer(layer)

A general tip to avoid issue with syntax in setSubsetString is

  • add the layer manually with the GUI,
  • use the filter on the layer through the GUI
  • select the layer in the layer tree in the GUI
  • open the QGIS Python console
  • type within the console iface.activeLayer().subsetString() and see the string you will need to set in your setSubsetString.

You will never do the mistake again and useful for more complex expressions.

0
7

Pay attention to quotes: Subset string is an expression. You have to use single quotes for string values. A text placed between single quotes ('VSR') is interpreted as a string. Double quotes will give you the value of the related field value ("GAMME_DE_S"). Fields can also be used without quotes as you did (GAMME_DE_S). No need to quotes for numbers (3.14).

Therefore, you have two options:

  1. "GAMME_DE_S = 'VSR'"
  2. "\"GAMME_DE_S\" = 'VSR'"

If you need to use a number, use, for example, "GAMME_DE_S = 3.14"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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