1

in my QGIS plugin, one of the dialog has a QtWidget table where the user can add items to the columns.

Each column of the table is a single list and the final result is a dictionary where the keys are the column name and the values are the single entries, like:

# example of single lists
sp = [1, 2, 3]
th = [0.2, 0.3, 0.1]

#example of dictionary
dic = {'stress': sp, 'thick': th}

From the dictionary I need to create a memory layer (no needs to have a spatial layer, just a table one). This memory "table" should have an attribute table where the files are the dictionary keys and the features are the dictionary values:

====== =====
stress thick
====== =====
1       0.2
2       0.3
3       0.1

Any suggestion?

EDIT

I made some progress.

from PyQt4.QtCore import QVariant
# create a memory layer 
vl = QgsVectorLayer('Point', 'layer' , "memory")
# data provider
pr = vl.dataProvider()

# lists of values, dictionary and list of field type, just as example
sp = [1, 2, 3]
tt = [10, 20, 30]

dd = {'stress':sp, 'thick':tt}
var = [QVariant.Int, QVariant.Int]

# create the fields of the layer with the dictionary keys
for i in dd.keys():
    for j in var:
        pr.addAttributes([QgsField(i, j)])

# update the fields
vl.updateFields()

until here is fine, but what I'm not able to do is to loop over the dictionary values and add them to the attribute table.

The workflow should be like this:

# start editing
vl.startEditing(

ft = QgsFeature()

# new attributes, if just one for each field
ft.setAttributes([1,10])

# send to data provider
pr.addFeatures([ft])

# commit the changes
vl.commitChanges()

But, how can I add many features in a single setAttributes method?

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.