1

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?

3 Answers 3

0

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

provider.select([35])
1
  • Hm, ok, that will shorten my code a little. Thanks! Unfortunatelly it doesn't seem to change the result. It still returns "None"… Sep 20, 2012 at 8:17
0

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!

0

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

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.