[GIS] get value from attribute table and change symbology with QGIS and Python

pythonqgissymbology

I'm newbie developing plugins for QGIS using Python, this is the first one and it is very frustrating. Ok, this is the situation, I have a 1 point layer in QGIS. Its attribute table has 4 fields and 1 row:

ID|Estation|Data|Estate

1     1     20  "Green"

What I'm trying to do with my plugin is to get the string data from "Estate" field and check the string data:

If string is "Green", the one point layer symbology will turn to green.

If string is not "Green", the one point layer symbology will turn to red.

The last part of this plugin is to refresh every X seconds to check "Estate" field, and change the symbology of this point layer if the "Estate" field has changed.

This is what I have done so far in my python script, I put from the run method:

# run method that performs all the real work
def run(self):

    # create and show the dialog
    dlg = PlayMonitoringDialog() 
    # show the dialog
    dlg.show()
    result = dlg.exec_() 
    # See if OK was pressed
    if result == 1: 
      # do something useful (delete the line containing pass and
      # substitute with your code
      def h():

        self.iface.mapCanvas().refresh
        layer = self.iface.activeLayer()
        Estado = layer.attributeDisplayName(3)
        if Estado == "green":
          props = { 'color' : '0,255,0' }
          sl = QgsSymbolLayerV2Registry.instance().symbolLayerMetadata("SimpleMarker").createSymbolLayer(props)
          s = QgsMarkerSymbolV2([sl])
          layer.setRendererV2(QgsSingleSymbolRendererV2(s))
        else:
          props = { 'color' : '255,0,0' }
          sl = QgsSymbolLayerV2Registry.instance().symbolLayerMetadata("SimpleMarker").createSymbolLayer(props)
          s = QgsMarkerSymbolV2([sl])
          layer.setRendererV2(QgsSingleSymbolRendererV2(s))
        if hasattr(layer, "setCacheImage"): layer.setCacheImage(None)
        layer.triggerRepaint()
      lanza()


  def lanza():
    t=threading.Timer(3.0,h)
    t.start()
  lanza()

It doesn't work, so I hope someone can help me. I have seen the small examples in http://www.qgis.org/pyqgis-cookbook, I have checked http://qgis.org/api/index.html and I have looked for examples on the Internet, but I still don't know how to solve the problems in my script.

Best Answer

It looks as though your problem is where your functions are defined. You should define all your functions at the beginning of your script, after the import, rather than inside of another function. If you need to use a function inside another, define it first and then call it within the second function. For example, you call lanza() in your first function, but you don't define it until afterwards. Rearranging your functions would take care of the basic Python problems. Any other problems would have to be answered by someone with more QGIS Python experience than I have :).