1

This Question is a follow up Question to this one I recently asked.

In my plugin I have a function that clips rasters by mask and I would like that the function returns the raster layer object. And then in another function I can get the Object. That's the code so far:

def clipRaster(self):
    wasserstand = self.getRasterLayer()
    outFile = os.path.join(QgsProject.instance().homePath(), "rtemp.tiff")
    gebeude = self.getVectorLayer()
    clip = processing.run('gdal:cliprasterbymasklayer',{'INPUT': wasserstand,'MASK': gebeude,
                   'NODATA': -1, 'ALPHA_BAND': False, 'CROP_TO_CUTLINE': True, 'KEEP_RESOLUTION': True,
                   'OPTIONS': "", 'DATA_TYPE': 5, 'OUTPUT': outFile})

    rlayer = QgsRasterLayer(clip['OUTPUT'])

    #rlayer = QgsRasterLayer(path_to_tif, "SRTM layer name")

    return rlayer

def getclip(self):
    clip = self.clipRaster()

    self.iface.addRasterLayer(clip)

    #iface.addRasterLayer("/path/to/raster/file.tif", "layer name you like")

Unfortunately, the error message I get is the following:

TypeError QgisInterface.addRasterLayer() arguments did not match any overloaded call overload 1 argument 1 has unexpected type 'QgsRasterLayer' overload 2 argument 1 has unexpected type 'QgsRasterLayer'

Why isn't it working? "outFile" defines the path and name of the raster, the processing algorithm creates a raster layer and puts it into the "outFile" directory. To create a new raster the function QgsRasterLayer() needs a path and layer name which is both in outFile, thus the raster is now saved in the rlayer variable. Finally, iface.addRasterLayer(clip) adds this object. It makes sense doesn't it? :).

Can someone explain my mistake?

2

If you recall from your previous question, the method iface.addRasterLayer() takes 2 string arguments- the file path and layer name as parameters. You are passing it a raster layer object, hence the error is telling you that argument 1 has the unexpected type 'QgsRasterLayer'.

You can use the addMapLayer() method which belongs to the QgsProject class instead. You can pass this method the raster layer object returned by your clipRaster() function.

QgsProject().instance().addMapLayer(clip)

Since this is in a plugin you will have to add QgsProject to your qgis.core imports.

By the way, I would recommend giving your raster layer a name when you create it:

rlayer = QgsRasterLayer(clip['OUTPUT'], 'Wasserstand_clipped') # call it whatever you want

After all, do you really want an un-named raster layer in the table of contents panel?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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