6

It is my second day on PyQGIS. Not sure why layer doesn't return anything.

Can anyone help me on this?

Code:

#!/usr/bin/python
from qgis.core import *
from qgis.utils import *
from PyQt4.QtCore import *

def main():
  qgis_prefix="/usr"    
  QgsApplication.setPrefixPath(qgis_prefix, True) 
  QgsApplication.initQgis()
  app = QgsApplication([], False)

  uri = "elevp.csv?delimiter=%s&xField=%s&yField=%s&elevField=%s" % (";","x","y","elev")
  vlayer = QgsVectorLayer(uri, "test", "delimitedtext")
  QgsMapLayerRegistry.instance().addMapLayer(vlayer)
  #print(QgsMapLayerRegistry.instance().mapLayers())


  #iface.mapCanvas().setSelectionColor( QColor("red") )
  layer = iface.activeLayer()
  print(layer)


# Run main wrapper codes
main()
0

1 Answer 1

16

You are creating a standalone pyqgis application. In a standalone application there is no iface.

Iface is provided by the QGIS desktop application to provide access to certain internals of the desktop application. Since there is no desktop application in the standalaone app (you are only using the QGIS libraries) there is also no possibility to have an iface available to give access to this non-existent software.

Or put differently, in the QGIS desktop application, iface.activeLayer() gives access to the currently selected layer in the legend. By default there is no legend in your standalone app, so there is no active layer.

So the question is actually which layer do you want? To the one layer which you created you already have a reference in vlayer so you should just continue to use that.

0

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.