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


2 Answers 2






Then to add the layer

if not layer.isValid():
    print("Layer failed to load!")

A general tip to avoid issues 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.


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 for 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 and acknowledge you have read our privacy policy.

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