# Rendering image in QGIS from custom plugin

How is it possible to render TIFF image from the path in the custom plugin? I tried to do like this:

canvas = QgsMapCanvas()
layer = QgsRasterLayer('my.tif',
'mytif',
'gdal')
canvas.setExtent(layer.extent())
canvas.setLayers([layer])
canvas.show()


also tried iface.addRasterLayer() and gsMapLayerRegistry.instance().addMapLayer(layer) - these two ways are definitely workable from the qgis python console however in the plugin I have warnings like

    Warning: QObject::setParent: Cannot set parent, new parent is in a different thread
Warning: QObject::connect: Cannot queue arguments of type 'QList<QgsMapLayer*>'
(Make sure 'QList<QgsMapLayer*>' is registered using qRegisterMetaType().)


and nothing is rendered.

I'm trying to do it from the separate class in the plugin package if it is a necessary information.

The __init__() method in your main plugin class should create a reference to the qgisinterface object as a class attribute e.g. self.iface. You should access this self.iface object and load your raster layer like this:

self.iface.addRasterLayer(path, 'My Raster')


I have added a minimal working plugin structure based on the example by Martin Dobias here.

I'm not sure from your question if you want to load your raster using a relative path to a tif file in the plugin directory or just an absolute path to a locally saved file. I have included examples of both.

to test this example, create a new directory in your qgis plugins folder. Save the script below as __init__.py and place it in this directory.

import os

from PyQt5.QtWidgets import QAction

def classFactory(iface):
return MinimalPlugin(iface)

class MinimalPlugin:
def __init__(self, iface):
self.iface = iface

def initGui(self):
self.action.triggered.connect(self.run)

self.iface.removeToolBarIcon(self.action)
del self.action

def run(self):
#Using relative path to load a tif file located in the
#plugin directory
folder = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(folder, 'my.tif')

#Or uncomment and change the path below to use an
#absolute path to a tif file on your local system

#path = 'C:\\path\\to\\my.tif'



Also save the following as a text file called metadata in the same directory:

[general]
name=MinimalPlugin
description=Minimal plugin