I want to develop a simple plugin and try to get started with Python in QGIS.

However, I have already run into troubles just loading my data properly. From the cook book I am using the code below successfully to add my layer in QGIS. But it won't retrieve information from my layer:

uri = QgsDataSourceURI()
#set host name, port , database name, username and password
uri.setConnection("localhost", "5432", "local_db", "postgres", "postgres")
#set database schema, table name, geometry column and optionaly subset(WHERE clause)
uri.setDataSource ("friluftsliv", "climbing", "geom")
# Defining the layer name and layer type for QGIS?
climbing=QgsVectorLayer (uri .uri() ,"Climbing","postgres")
# Adding a layer to registry

Now I am trying to retrieve information from my layers using:

for field in climbing.pendingFields():
  print field.id_0()

This does not give me anything, no errors nor info... I have 27 rows in my table. It has SERIAL and PK in database. From http://www.qgistutorials.com/en/docs/getting_started_with_pyqgis.html I tried with nothing to be printed.

for field in layer.getFeatures():
  print field['id_0']

I have another layer called hiking that I try to add with the same code as above. That layer don't get added to the registry. I don't get any errors when I defining the layer but if I run QgsMapLayerRegistry.instance().mapLayers() it does not come up in the list...

Any advice on what might be wrong?

  • What is climbing=QgsVectorLayer (uri .uri() ,"Climbing","postgres") supposed to do? Is that really the exact code you're trying to run? Including the space – BradHards Dec 14 '15 at 10:40
  • That is my version of vlayer = QgsVectorLayer(uri.uri(), "layer name you like", "postgres") copied from the QGIS python Cookbook. I think it define the data source for a layer. When I try to iterate the layer I get "AttributeError: 'QgsField' object has no attribute 'id' altough it is an existing field. Will try to do the same with the shape file they use in the example rather than my own PostGIS layer. – geogrow Dec 14 '15 at 12:11
  • The second "postgres" argument in this statement, uri.setConnection("localhost", "5432", "local_db", "postgres", "postgres"), should be the password, are you referencing it as the password? – artwork21 Dec 14 '15 at 13:03
  • yeah postgres is the default password I am using in my local test postGIS db. I can communicate with my db. I can add my layers, but nothing get printed when i try to iterate through the layer using for field in climbing.pendingFields(): . I can see the layer registered in the registry. – geogrow Dec 14 '15 at 13:07

Your Answer

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

Browse other questions tagged or ask your own question.