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.")
else:
name = self.layer_names[-1].strip('[]')
pstr = "Removing overlay: %s" % name
print(pstr)
layer = self.project.instance().mapLayersByName(name)[0]
self.project.instance().removeMapLayer(layer)
self.QMC.refreshAllLayers()
self.layer_names.pop(-1)
self.layers.pop(-1)
return
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() ):
self.layer_names.extend(layer_title)
self.project.instance().addMapLayer(layer)
self.map_canvas.setExtent(layer.extent())
self.layers.insert(0,layer)
self.map_canvas.setLayers(self.layers)
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?