Advertisements

After loading a vector layer, viewing its attributes is the next logical step.

We previously noted that the addVectorLayer() function returns a QgsVectorLayer object. In this context “returns” means that this function creates an object that we can use. Telling the iface to add a vector layer is similar to telling a restaurant to make you a pizza. If everything works out (whether it’s cooking or object creating), you’ll get a pizza to eat – or a vector layer to continue working with.

We need to give a name to the returned QgsVectorLayer object so that we can refer to it later. We’ll chose to call it vlayer:

uri = "E:/Geodata/NaturalEarth/vector_v4/natural_earth_vector.gpkg_v4.1.0/packages/natural_earth_vector.gpkg|layername=ne_10m_admin_0_countries"
vlayer = iface.addVectorLayer(uri, "countries", "ogr")

When we call the addVectorLayer() function, a lot of things happen in the background: QGIS checks the vector layer path and tries to open it using the provider that we specified. If successful, it adds the layer to the project using the name we provided. It also makes sure that the map is redrawn so that we can actually see the new layer on the map. And last but not least, it returns the newly created QgsVectorLayer object so we can use it later.

Now that we have our vlayer object we can do something with it – like opening its attribute table using the iface.showAttributeTable function:

iface.showAttributeTable(vlayer)

Every time we run addVectorLayer(), QGIS creates a new QgsVectorLayer object and adds the layer to the project. If you want to stop a particular piece of code from being executed, you can comment it out by putting a hashtag in front of the code:

uri = "E:/Geodata/NaturalEarth/vector_v4/natural_earth_vector.gpkg_v4.1.0/packages/natural_earth_vector.gpkg|layername=ne_10m_admin_0_countries"
#vlayer = iface.addVectorLayer(uri, "countries", "ogr")
iface.showAttributeTable(vlayer)

Instead of just opening the attribute table dialog, we can of course use the attributes in code as well. As with the iface object we dealt with earlier, QqsVectorLayer objects have a whole lot of functions (methods). To get a list of the attribute (or field) names printed to the console, we can go through the layer’s fields provided by the fields() function. This function returns a QgsFields object. To print all field names to the console, we can use a for loop:

for field in vlayer.fields():
    print(field.name())

You can read these two lines of code as: For each field in the vector layer’s fields, print the field name. In this case, fields() is a function of our vector layer object while field is a variable name that can be chosen freely.

In a similar way, we can print the ADMIN attribute value of our layer’s features using the getFeatures() function:

for feature in vlayer.getFeatures():
    print(feature["ADMIN"])

This code is the first example of how Python code is structured by indenting lines of code (i.e. putting spaces or tabs at the beginning of the line). If you omit the spaces before the print function, you’ll see an error. The correct number of spaces (or whether to use spaces or tabs) has been a topic of many discussions. By default, the code editor will insert 4 spaces. It is important to be consistent and avoid mixing different indentation styles. It’s not uncommon to run into errors because tabs were mixed with spaces.

These are the basics of viewing vector layer attribute names and values. You also saw how to write a for loop to iterate through a vector layer’s  fields and features.

Next


PyQGIS 101 is a work in progress. I’d appreciate any feedback, particularly from beginners!

Advertisements
8 comments
  1. bwilkes said:

    My feedback so far would be to add instructions on how to save code after this lesson. I closed QGIS but neglected to save my code, and am now having to recreate it in order to continue with the next lesson.

    • Good point, thanks! I’ve added a reminder to “Loading a vector layer”.

  2. Chris said:

    Probably a stupid question but… i’m beginning.
    If you comment the “vlayer = iface.addVectorLayer(uri, “countries”, “ogr”)”
    How does the call for vlayer in “iface.showAttributeTable(vlayer)” can possibly work ?

    For your understanding i execute your code from a .py file that is like this at the moment:

    uri = “D:/MNT/GEOFLA.gpkg|layername=Communes”
    #vlayer = iface.addVectorLayer(uri, “COMMUNES”, “ogr”)

    for feature in vlayer.getFeatures():
    print(feature[“NOM_COMM”])

    Thanks !

    • Hi Chris,
      If you run vlayer = iface.addVectorLayer(uri, “countries”, “ogr”) once, QGIS will remember it. You can test it by typing vlayer into the Python console and pressing enter. It should return .
      I’ve introduced the possibility of commenting code out in this chapter since QGIS will keep on adding new layers based on the same input dataset if you call addVectorLayer over and over.

      • Chris said:

        Hey ! Thanks for the answer. It makes sense: The variable keep it’s value until you change it or you close your QGIS. Just to be precise (and maniac ?), is it QGIS or Python that “remember” the value ?

      • It only exists in the context of the Python Console, afaik.

  3. Pedro Bittencourt said:

    Hi,

    I started learning Python in February this year and my main goal has always been to use it in QGIS.

    Unfortunately I couldn’t manage to pass the first “for loop” and I get the following error:

    “AttributeError: ‘QDialog’ object has no attribute ‘fields'”

    Am I doing something wrong?
    Thank you.

  4. Pedro Bittencourt said:

    Hi, I managed! My mistake!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: