2

I am writing my first Python plugin. There was a problem during work. The plugin is designed to select a raster and calculate the statistics for the area bounded by the vector. I have created a list of rasters, but I do not know how to refer to the selected raster in the further part of the plugin to calculate statistics for it. The following code is created.

List of raster layers:

def create_layer_list(self):
    ''' Build list of layers'''
    self.dialog.chooseCombo.clear()
    self.layers = list(self.registry.mapLayers().values())
    #self.layers = self.iface.legendInterface().layers()
    layer_list = [""]+[layer.name() for layer in self.layers]
    self.dialog.chooseCombo.addItems(layer_list)

Main function for counting statistics:

def get_statistic(self):

      index2 = self.dialog.chooseCombo.currentIndex()
      rlayer = self.layers[index2].layer_list()
      provider = rlayer.dataProvider()

      for band in range(1, rlayer.bandCount() + 1):
        stats = provider.bandStatistics(band, QgsRasterBandStats.All, self.extent, 0)
        min = stats.minimumValue
        max = stats.maximumValue
        mean = stats.mean
        statsGathered = stats.statsGathered
        results= print ('min: {:.2f}, max: {:.2f}, mean: {:.2f}, statsGathered: {:.2f}'.format(min, max,mean,statsGathered)) 
        self.dialog.textlabelLayout.setText(results)

Unfortunately, Python throws an error when indexing ..

1 Answer 1

1

Try referencing the selected layer by name:

def get_statistic(self):
    selected_layer = self.dialog.chooseCombo.currentText()
    rlayer = QgsProject.instance().mapLayersByName(selected_layer)[0]
    provider = rlayer.dataProvider()
2
  • 1
    I changed QgsMapLayerRegistry to QgsProject and it worked! Thank You!
    – iza4400
    Oct 15, 2019 at 19:55
  • @iza4400 - Apologies, you are indeed correct :)
    – Joseph
    Oct 16, 2019 at 9:01

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.