[EN]Developing a QGIS Plugin: Working Only with Selected Features

In QGIS, many operations should only be applied to a subset of the data: a specific set of features selected by the user.

In this article, we will learn how a QGIS plugin can detect, validate, and process only the selected features, without risking unintended modifications to the entire layer.

The goal is twofold: to make processing safer and to respect the user’s intent, while keeping the code simple and accessible to beginners.


Modifying a QGIS layer can feel risky, especially when you are new to plugin development. Our guide Modifying a QGIS Layer Without Putting It at Risk explains how to use editing mode, commit or rollback changes, and safely update layers and attributes. Understanding these concepts will help you protect your data while making your plugins genuinely useful.


Why Work Only with Selected Features?

In QGIS, users rarely select features by accident.

A selection almost always expresses a specific intention:

“I want to work with these features, not the others.”

A plugin that ignores the current selection and processes the entire layer:

  • can produce serious mistakes,
  • breaks user trust,
  • becomes risky to use.

As a general rule, a well-designed plugin should respect the active selection.


How QGIS Handles Feature Selections

In QGIS:

  • the selection belongs to the layer,
  • it is temporary and can change at any time,
  • it is directly accessible through the PyQGIS API.

At any moment, a vector layer knows:

  • how many features are selected,
  • which features are selected.

This makes selections a powerful and reliable way to target specific data.


Retrieving the Active Layer

In most plugins, the first step is to retrieve the currently active layer.

layer = iface.activeLayer()

The first safety rule is simple:

if not layer:
return

No active layer means no action should be performed.


Checking Whether Features Are Selected

Before starting any processing, your plugin should verify that the user has actually selected something.

selected_features = layer.selectedFeatures()

if not selected_features:
# no selected features
return

At this point, the plugin already knows whether it should:

  • continue processing,
  • or stop gracefully.

This simple check prevents many user errors.


Processing Selected Features

The selectedFeatures() method returns a list of QgsFeature objects.

You can therefore iterate through them easily:

for feature in selected_features:
# process each feature

Each feature contains:

  • its attributes,
  • its geometry,
  • its unique identifier.

This is everything your plugin needs to perform targeted operations.


A Simple Example: Reading an Attribute

Once you have access to the selected features, you can retrieve their attribute values just as you would with any other QgsFeature.

For example:

for feature in selected_features:
value = feature[“population”]

In this example, the plugin reads the value of the field named population for each selected feature.

If the field does not exist, an error will occur.

This is why it is important to verify the structure of the layer before accessing attributes. As we saw in previous articles, a plugin should never assume that a field is always present.


Modifying Attributes Safely

Updating selected features requires the layer to be in editing mode.

Before making any changes, your plugin should verify whether editing is already enabled.

if not layer.isEditable():
layer.startEditing()

You can then update the selected features:

for feature in selected_features:
feature[“status”] = “processed”
layer.updateFeature(feature)

Finally, save the changes:

layer.commitChanges()

A plugin should never silently modify data without the user’s knowledge.

Later in this series, we will see how to request confirmation before committing changes.


Active Selection ≠ Filter ≠ Temporary Layer

QGIS provides several ways to work with a subset of data.

Although they may appear similar from the user’s perspective, they behave very differently inside a plugin.

Understanding these differences is essential for writing reliable tools.

Active Selection

An active selection:

  • belongs to the layer,
  • is visually highlighted,
  • is accessible through selectedFeatures(),
  • changes whenever the user updates the selection.

This is the safest and most explicit mechanism for most plugins.

Layer Filter

A layer filter:

  • hides features that do not match a query,
  • makes the layer appear smaller,
  • affects what the user sees.

However, unless additional precautions are taken, a plugin may still access features that are hidden by the filter.

A poorly designed plugin can unintentionally modify features that are not visible on the screen.

Temporary Layer

A temporary layer:

  • is usually created by a processing tool,
  • contains a copy or subset of the original data,
  • is independent from the source layer,
  • may disappear when the project is closed.

Temporary layers are excellent for testing, visualization, and intermediate processing, but they are not always appropriate when updating source data.


Key Takeaway

These three concepts are fundamentally different:

  • Selection = explicit user intent
  • Filter = partial view of the data
  • Temporary layer = working copy

In most business-oriented plugins, the active selection is the best starting point.


What If No Features Are Selected?

Sooner or later, every plugin developer faces the same situation:

The user launches the tool without selecting any features.

What should the plugin do?

There are two common approaches.

Option 1 – Block the Action

The safest solution is simply to stop processing and inform the user.

For example:

Please select at least one feature before running this tool.

This approach avoids ambiguity and prevents accidental modifications.

In most cases, this is the safest option.

Option 2 – Offer an Alternative

Another possibility is to ask the user what they want to do.

For example:

No features are currently selected. Do you want to apply this operation to the entire layer?

This approach provides more flexibility while still keeping the user in control.

The important principle is that the plugin should never make this decision silently.

Always give users a choice.


Typical Use Cases

Working only with selected features is essential for many common GIS tasks.

For example:

  • recalculating an attribute for a subset of features,
  • correcting specific geometries,
  • applying business rules to a targeted group of objects,
  • preparing data before export,
  • validating a specific set of records.

In practice, a large proportion of business-oriented plugins should work this way.

Users expect tools to operate on the features they have explicitly selected.


Why This Matters

Respecting the current selection is not just a technical detail.

It is a design principle.

A selection represents an explicit action performed by the user.

Ignoring it often leads to confusion, unexpected results, and loss of confidence in the tool.

By contrast, a plugin that respects the active selection behaves in a predictable and professional manner.


Key Points to Remember

Before moving on, remember these essential ideas:

  • A selection represents user intent.
  • A well-designed plugin should respect that intent.
  • The required PyQGIS code is simple and easy to read.
  • Safety comes from good design choices, not from complex code.

Many beginner developers assume that making a plugin safer requires sophisticated programming.

In reality, the most important protection often comes from a few simple checks performed at the right time.


What You Have Learned

By the end of this article, you now understand:

  • how to retrieve the active layer,
  • how to detect selected features,
  • how to process only the selected features,
  • how to safely modify selected objects,
  • why selections, filters, and temporary layers are fundamentally different.

Your plugin can now work on a targeted subset of data rather than blindly processing an entire layer.

This is a major step toward building professional and reliable QGIS plugins.


What’s Next?

In the next article, we will explore a closely related topic:

how to modify features without putting data at risk.

We will learn how to:

  • work safely in editing mode,
  • commit or cancel changes,
  • protect user data,
  • build plugins that users can trust.

A useful plugin is not only one that performs a task correctly—it is also one that protects the data it modifies.


Si cet article vous a intéressé et que vous pensez qu'il pourrait bénéficier à d'autres personnes, n'hésitez pas à le partager sur vos réseaux sociaux en utilisant les boutons ci-dessous. Votre partage est apprécié !

Leave a Reply

Your email address will not be published. Required fields are marked *

Are you human? Please solve:Captcha