I'm developing a very simple QGIS plugin to calculate raster average by using GDAL. It uses a QgsMapLayerComboBox and a filter to select only raster layers. However, it needs to select twice a layer at the Combo Box to produce the expected results. The snipped code is:
. . . def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/AverageRaster/AverageRaster.png' self.add_action( icon_path, text=self.tr(u'To calculate raster average'), callback=self.run, parent=self.iface.mainWindow()) self.wcb = QgsMapLayerComboBox(self.dlg) self.wcb.setFixedWidth(220) self.wcb.move(140,40) self.wcb.setFilters( QgsMapLayerProxyModel.RasterLayer ) . . . def run(self): """Run method that performs all the real work""" #My code starts here layer = self.wcb.currentLayer() . . . self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. #My code starts here message = "the raster average of " + filename + " is = " + str(average) QMessageBox.information(None, "Raster Average", message) #My code ends here
At the next image, my Plugin is determining the average of ndvi.tif raster. If I want the average of utah_demUTM2.tif, the expected value is obtained only at the second chance. How can I get the average at the first selection of a layer at the QgsMapLayerComboBox.
Afterward that I tried out a lot of possibilities, I found a possible solution but, I don't like it very much because I have to click on icon plugin again and not on a OK button.
At the 'Property Editor' of Qt Designer, I unmarked the 'OK' button and I modified the label "Click on OK to get raster average" for this one: "Click on plugin icon again to get raster average".
After reloaded the plugin, I observed that the order in the Combo Box was alphabetic.
When I selected anyone of these layers (see above image) and I clicked on icon plugin, its behavior was always as expected and the principal Dialog never closed.
I changed the QMessageBox for a QTextBrowser and put again the OK button at the widget Dialog. In this case, I could observe that the QgsMapLayerComboBox has the expected behavior when I select the raster layer. The problem is when I clicked on the OK buttom. The Dialog was closed and I need to launch the plugin again to see the results. It is possible to keep the window Dialog open when the OK button is clicked?