Applying conditional label opacity in QGIS

conditionalexpressionlabelingqgistransparency-opacity

I'm working with QGIS 3.16 Hannover.

I've got one layer with all Spanish provinces (provincias) and, on top of it, several layers with the regions (AND, ARA, AST…). Each province pertains to one region and each region may contain one or more provinces.

I want to label the provincias layer with different opacity, depending on whether their region layer is visible or not. Here is where I try to set the differential label opacity

enter image description here

And this is the result I intend to achieve (layer AND, visible)

enter image description here

And I've tried the following code, without success:

case
   when (overlay_within('AND') and is_layer_visible('AND')) then 50 
   when (overlay_within('ARA') and is_layer_visible('ARA')) then 50
   [...]
   else 20
end

It only works with the first region, and this is what happens when I make visible the next one (ARA)

enter image description here

What's wrong?

Best Answer

Click data driven override for label opacity and select Assistant. Add the following expression, set values from/to to 0 and 1, and Opacity from / to to the opacity values you like (see screenshot at the bottom).

The expression works like this:

  1. The idea is to first get an array of all layers with @layer_ids (line 3)
  2. Then for each of these layer (using array_foreach, line 2) check if (line 4) it is visible (line 5) and if so, return it's name (line 6), otherwise an empty string (line 7).
  3. Use array_contains (line 1) to check if the resulting array from step 2 contains a region's layer name that corresponds to the value of the attribute field "region" (2nd last line) in the provinces layer. In this case, the result is 1, otherwise 0.

The final expression looks like:

array_contains(
    array_foreach (
        @layer_ids,
        if (
            is_layer_visible( @element),
            layer_property( @element, 'name'),
            ''
        )
    ), 
    "region"
)

Replace region in the second last line with the name you use as fieldname in the provinces layer. Be sure these values correspond to the names of the layers (as can be seen on the screenshot).

By the way: it is always a good idea to provide the data + project file you work with, at least dummy data. This saves time for you as well as the one answering (time to set up a testing project and time adapting the answer to the values and names you use in your project).

enter image description here