Setting layer identifiable, seachable and removable with Python in QGIS 3?

I tried to understand the behavior of the setFlags method by see on a vector layer the results of :

vl = iface.activeLayer()
flags = 1
vl.setFlags(QgsMapLayer.LayerFlag(flags))
# result : the layer is identifiable and required

I looked at the Python API doc for QgsMapLayer, in these attributes and :

  • Identifiable = 1 (= 2 power 0)
  • Removable = 2 (= 2 power 1)
  • Searchable = 4 (= 2 power 2)

If we draw a binary table :

Num2 power 22 power 12 power 0
   0          0             0             0      
   1          0             0             1      
   2          0             1             0      
   3          0             1             1      
   4          1             0             0      
   5          1             0             1      
   6          1             1             0      
   7          1             1             1      

and a table of project layer settings (DataSource tab) with the result of vl.setFlags(QgsMapLayer.LayerFlag(Num)), 1 as True and 0 as False :

NumSearchable Required Identifiable
   0           0               1               0       
   1           0               1               1       
   2           0               0               0       
   3           0               0               1       
   4           1               1               0       
   5           1               1               1       
   6           1               0               0       
   7           1               0               1       

  • Identifiable behavior equals 2 power 0
  • Searchage behavior equals 2 power 2
  • but Removable behavior is the inverse of 2 power 1.

... and wait ! Required is the inverse of Removable.

For set these settings for a layer in a project, the code is :

vl = activeLayer()
identifiable = QgsMapLayer.Identifiable
searchable = QgsMapLayer.Searchable
removable = QgsMapLayer.Removable

# for a non-required and identifiable layer
vl.setFlags(QgsMapLayer.LayerFlag(identifiable + removable))

# for a searchable only layer
vl.setFlags(QgsMapLayer.LayerFlag(searchable + removable))

# for a searchable and required layer
vl.setFlags(QgsMapLayer.LayerFlag(searchable))

Or a function :

def layer_settings(vectorLayer, isIdentifiable=True,
    isSearchable=True, isRequired=False):

    flags = 0
    if isIdentifiable:
        flags += QgsMapLayer.Identifiable

    if isSearchable:
        flags += QgsMapLayer.Searchable

    if not isRequired:
        flags += QgsMapLayer.Removable

    vectorLayer.setFlags(QgsMapLayer.LayerFlag(flags))

vl = iface.activeLayer()
# for an identifiable and required layer
layer_settings(vl, True, False, True)