[GIS] Select and use raster layer from python

pyqgispyqt4qgis-plugins

I'm a developer but this is the first experience with python and QGIS Plugin, I want make a plug-in for Remote Sensing Index.
I have followed this basic tutorial https://www.youtube.com/watch?v=ZI3yzAVCK_0 and in this moment I have one dropdown with layer selection.

I correctly loaded the layer but I want see only the raster layer with multiple band for raster calculation, is it possible to filter it?

After at item selection from the dropdown list, load the band in other dropdown list for right association (green, blue, red, RedEdge ,Near IR).

Is it possible to make? What is the class prop to read?

This is almost the UI

screen

Best Answer

Hopefully the following will help get you started, I've added comments to try and explain how it works.

Essentially, you can use a QgsMapLayerComboBox to filter out all layers loaded in QGIS and only have it list the multiband rasters. You can then define a function which will read the selected layer and populate the combo boxes for the bands (note that I only added the standard red, green and blue bands):

def raster_bands(self):
    # Read current item in raster layer combobox
    rlayer = self.dockwidget.mMapLayerComboBox.currentText()
    # Match name of current item with layer in table of contents
    selected_rlayer = QgsMapLayerRegistry.instance().mapLayersByName(rlayer)[0]
    # Clear band combo boxes
    self.dockwidget.red_comboBox.clear()
    self.dockwidget.green_comboBox.clear()
    self.dockwidget.blue_comboBox.clear()
    # Add band numbers to associated combo boxes
    self.dockwidget.red_comboBox.addItem(str(selected_rlayer.renderer().redBand()))
    self.dockwidget.green_comboBox.addItem(str(selected_rlayer.renderer().greenBand()))
    self.dockwidget.blue_comboBox.addItem(str(selected_rlayer.renderer().blueBand()))

# Set first filter for QgsMapLayerComboBox to only populate with raster layers
self.dockwidget.mMapLayerComboBox.setFilters(QgsMapLayerProxyModel.RasterLayer)
# Create an empty list
rlayer_list = []
# Loop through all loaded layers in table of contents
for layer in QgsMapLayerRegistry.instance().mapLayers().values():
    # If layer is a raster and it is not a multiband type
    if layer.type() == 1 and layer.renderer().type() != "multibandcolor":
        # Add to list
        rlayer_list.append(layer)
# Set second filter to only populate with multiband rasters
self.dockwidget.mMapLayerComboBox.setExceptedLayerList(rlayer_list)

# Run function on startup
raster_bands(self)
# When raster selection is changed, update combo boxes
self.dockwidget.mMapLayerComboBox.currentIndexChanged.connect(raster_bands)

Result:

Raster bands