I am working on a PyQGIS (QGIS 3.10) application to overlay data on OpenStreetMap raster tiles. I am adding a function that removes the most recently added layer from the project and refreshes the map. It looks like this:

def rmv_layer(self):

    if not self.layer_names:

        print("No overlay to remove.")


        name = self.layer_names[-1].strip('[]')
        pstr = "Removing overlay: %s" % name
        layer = self.project.instance().mapLayersByName(name)[0]


where self.layer_names is a list that is updated with the layer name after one is added to the map canvas in a separate add_overlay class while the name of the removed layer and the layer itself is erased here using pop. This code works fine the first time around. However, when adding a new layer to the map canvas using the following code:

def add_layer(self):

   layer = QgsRasterLayer(self.new_raster,self.layer_title,"gdal")

   if ( layer.isValid() ):


I get this error:

TypeError: index 1 has type 'QgsRasterLayer' but 'QgsMapLayer' is expected

I'm not sure what the root issue is since QgsMapLayer is the base class for QgsRasterLayer, QgsVectorLayer, etc. The self.layers list is set up to where it always retains the base OpenStreetMap tiles in the 'registry'. This error only occurs when I remove and refresh. If I keep adding layers it's happy, and I have to refresh the map canvas otherwise the layer will still be displayed (e.g., commenting out self.QMC.refreshAllLayers() inherently does nothing). This error also occurs without the self.layers.pop(-1) line in the first block.

Is there a better way to clear the most recent layer than this?

1 Answer 1


The most recent layer added was to the front of the QList<QgsMapLayer> object, so it had to be:


as it was still including the QgsRasterLayer info despite the feature being deleted. Also moved the refresh statement to the end. All works fine now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.