Introduction to PyQGIS

3. Create a Stage Volume Table with PyQGIS in QGIS

In the previous section we've calculated the volume corresponding to a specific elevation one by one.

In this section we're going to iteratively calculate the volume for a range of elevations and store the results in one table. For that purpose we need to write a PyQGIS script around the Raster Surface Volume tool.

All processing tools that you've run are stored in the history of the Processing Toolbox. Let's have a look and see how we can use that for our script.

1. In the Processing Toolbox click to open the history.

Algorithm history

There you find what we did in the previous section. Try to read what's written after

It contains the name of the tool: native: rastersurfacevolume. It contains a dictionary with all the inputs from the dialogue. That means that we can copy this and replace parts of the dictionary in a PyQGIS script with a variable. Here we should iterate for different LEVEL values from the minimum to the maximum elevation in the DTM.

2. Click Close to close the History dialogue.

3. In the main menu choose Plugins | Python Console to open the Python Console.

4. In the Python Console click to open the editor.

5. Go to this GitHub page:

6. Copy the Python code to the editor and save the script as

Read the comments to understand what happens in the code. Later we'll look in more detail at the script when we'll work with it outside of the QGIS GUI.

7. The only thing to change is to replace the projectPath and inputRasterDEM with your own names.

8. Save the script and click to run the script.

This is the result printed in the Python Console:

The script has also added a DEM layer and the StageVolume table to the Layers panel.

9. Click right on StageVolume and choose Open Attribute Table and inspect it.

Stage Volume Table

We have created the Stage Volume Table with the Level field in meters and the VolAbsKm3 field containing the volumes in km3.

In the next section we'll create the Stage Volume Curve using the Data Plotly plugin.

Note that you can also add the StageVolumeTool from GitHub to the Processing Toolbox. The tool then has a dialogue. You can download the tool from here: