2

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()
  • Try adding the full path to your "elevp.csv" file. E.g. uri = "file:///C:/Test/elevp.csv?delimiter=%s&xField=%s&yField=%s&elevField=%s" % (";","x","y","elev"). – Joseph Sep 25 '15 at 9:55
  • Tried, doesn't work. (Fyi, I'm using ubuntu server) – Eric T Sep 28 '15 at 4:03
  • The other issue may be with the PYTHONPATH to qgis libraries. You need to setup that before using this code. – osmjit Oct 1 '15 at 9:56
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post. – AndreJ Oct 1 '15 at 10:26
7

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.

  • Hi, I already solve this and posted the further issue that I am facing over here gis.stackexchange.com/questions/164596/… – Eric T Oct 2 '15 at 2:47
  • 2
    Hi, if that was the right answer, please mark it as correct. For the future: you are also able to answer your own questions, so they will help as reference for others experiencing the same problem. – Matthias Kuhn Oct 2 '15 at 8:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.