[GIS] How to programmatically delete all inner rings of a polygon layer

polygonpyqgispythonqgis

I have many polygon layers, each layer containing many polygons with inner rings. I know that you can delete a ring manually with QGIS (Edit -> Delete ring). I need the python equivalent to automatically process all my polygon layers.

Best Answer

This blog posts tells how to do it with SQL in PostGIS http://geospatial.commons.gc.cuny.edu/2013/11/04/filling-in-holes-with-postgis/

Spatialite has also ExteriorRing function http://www.gaia-gis.it/gaia-sins/spatialite-sql-latest.html so you do not need to have PostGIS installed. Is it necessary for you to do the job with python inside QGIS? The SQL looks like this:

UPDATE my_spatial_table t
SET geom = a.geom
FROM (
    SELECT gid, ST_Collect(ST_MakePolygon(geom)) AS geom
    FROM (
        SELECT gid, ST_NRings(geom) AS nrings, 
            ST_ExteriorRing((ST_Dump(geom)).geom) AS geom
        FROM my_spatial_table
        WHERE ST_NRings(geom) > 1
        ) s
    GROUP BY gid, nrings
    HAVING nrings > COUNT(gid)
    ) a
WHERE t.gid = a.gid;