Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I am trying to write a python plugin for QGIS that can convert three vector layers into an object File for an urban climate model. Unfortunately I am stuck again with a possibly easy question:

How can I save a column from the attribute table of a vector layer to a variable (for later use)?

For example, I have a layer with buildings (build) with the hight of the buildings in field 35. I want to save all the building hights into a variable (theINPolyHField).

I tried the following:

build = canvas.layer(2)
build_prov = build.dataProvider()

theINPolyHField = build_prov.select([35], build.extent(), False, False) # but returns "None"
build.selectedFeatureCount() # returns 0

What am I doing wrong?

share|improve this question
add comment

3 Answers 3

According to the PyQGIS Cookbook all four parameters of select() are optional, so try this

provider.select([35])
share|improve this answer
    
Hm, ok, that will shorten my code a little. Thanks! Unfortunatelly it doesn't seem to change the result. It still returns "None"… –  Dominik Froehlich Sep 20 '12 at 8:17
add comment
up vote 0 down vote accepted

After looking around for a while i analyzed another script and wrote me the following function:

def extract_attribute(layer, attribute_index): 
# function to extract a list of attributes from a layer
  qgis.mainWindow().statusBar().showMessage("Extracting layer fields")
  feature = QgsFeature()
  layer.dataProvider().select(layer.dataProvider().attributeIndexes())
  layer.dataProvider().rewind()
  attr_list = []
      while layer.dataProvider().nextFeature(feature):
      attributes = feature.attributeMap()
      attr_list.append(attributes[attribute_index])
return attr_list

There may be easier ways, but i think it does what i want… Thanks!

share|improve this answer
add comment

Just a note:

For QGIS 2.0 and higher this is different:

def extract_attribute(layer, attribute_index):
# function to extract a list of attributes from a layer
  qgis.mainWindow().statusBar().showMessage("Extracting layer fields")
  # Create an empty list to append all attributes
  attr_list = []
  # Iterating over the features (rows) in the vector layer 
  for feature in layer.getFeatures():
    # Iterating over all attributes (columns) of a feature (row)
    for attr in feature.attributes():
      attr_list.append(attr[attribute_index])
return attr_list
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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