3

I am trying to get the values of attributes of the selected features of a layer field by field and copy to another layer that I created in qgis with pyqgis.

Is here a example for this. Every example I found leaded me to the dead end.

2 Answers 2

2

OK so you want to know how to generate polygons centered on selected points in pyQGIS and retain all the attributes of the points in the new polygons? Here's a script to do that: Note that the code was written to apply to a points-containing example shape file I have. You need to remove the section which reads in my example file in order for it to use your 'selected' points features. note also that the result will be better if your layer is in a 'projected' projection such as UTM and not in lat/lon.

Finally, I need to reference the source for the polygon generator code: https://stackoverflow.com/questions/23411688/drawing-polygon-with-n-number-of-sides-in-python-3-2

import os
from PyQt4.QtCore import QSettings
import math

def polygon_generator(sides, radius=1, rotation=0, translation=None):
    one_segment = math.pi * 2 / sides

    points = [
        (math.sin(one_segment * i + rotation) * radius,
         math.cos(one_segment * i + rotation) * radius)
        for i in range(sides)]

    if translation:
        points = [[sum(pair) for pair in zip(point, translation)]
                  for point in points]
    QGisPoints=[]

    for point in points:
        QGisPoints.append(QgsPoint(point[0],point[1]))

    return QGisPoints

############OPEN A FILE AND SELECT POINTS ################
#Header to open a file, select the layer, then select all the objects in that layer
point_file_name="building_pnt.shp"
point_file_folder=r"G:\GARMIN\testshapes\AW30"
point_file_path=os.path.join(point_file_folder,point_file_name)
input_layer = QgsVectorLayer(point_file_path, "input layer", "ogr")
input_layer_data_provider=input_layer.dataProvider()
QgsMapLayerRegistry.instance().addMapLayer(input_layer)
QGisWKBType=input_layer_data_provider.geometryType()
qgis.utils.iface.setActiveLayer(input_layer)
qgis.utils.iface.zoomToActiveLayer()
input_layer.selectAll()
###################################################

#get active layer 
input_layer=qgis.utils.iface.mapCanvas().currentLayer()

#Get/set layer type for new memory layer
QGisLayerType="Polygon"
EPSG_code=int(input_layer_data_provider.crs().authid().split(":")[1])

#Create destination layer in memory
s = QSettings()
oldValidation = s.value( "/Projections/defaultBehaviour")
s.setValue( "/Projections/defaultBehaviour", "useGlobal" )
destination_layer=QgsVectorLayer(QGisLayerType+"?crs=epsg:"+str(EPSG_code)+"index=yes","memory layer","memory")
destination_layer.setCrs( QgsCoordinateReferenceSystem(EPSG_code, QgsCoordinateReferenceSystem.EpsgCrsId) )
s.setValue( "/Projections/defaultBehaviour", oldValidation )
destination_layer_data_provider=destination_layer.dataProvider()
QgsMapLayerRegistry.instance().addMapLayer(destination_layer)

#Generate attributes in destination layer
input_layer_attrib_names = input_layer.dataProvider().fields()
oldattributeList = input_layer.dataProvider().fields().toList()
newattributeList=[]
for attrib in oldattributeList:
  if destination_layer.fieldNameIndex(attrib.name())==-1:
    newattributeList.append(QgsField(attrib.name(),attrib.type()))
destination_layer_data_provider.addAttributes(newattributeList)
destination_layer.updateFields()

#Read in features and generate n-sided polygons with matched attributes
destination_layer.startEditing()
cfeature = QgsFeature()
polygon_radius=5
polygon_rotation=0
sides=8

for xfeature in input_layer.selectedFeatures():
#for xfeature in input_layer.getFeatures()
    cfeatures=[]
    xgeometry = xfeature.geometry()
    xval=xgeometry.asPoint().x()
    yval=xgeometry.asPoint().y()

    translation=[xval,yval]
    my_polygon=polygon_generator(sides,polygon_radius, polygon_rotation, translation)

    new_geom=QgsGeometry.fromPolygon( [ my_polygon ] )
    cfeature_Attributes=[]
    cfeature_Attributes.extend(xfeature.attributes())
    cfeature.setGeometry(new_geom)
    cfeature.setAttributes(cfeature_Attributes)
    cfeatures.append(cfeature)
    destination_layer_data_provider.addFeatures(cfeatures)
    destination_layer.commitChanges()
1
1

If the selected features and your created layer both share an identical column in their attributes tables. (ie maybe under ID they are both called FT001) then you can do a join and this will add additional attribute details from your selected feature layer. This is also handy if you want to just add a .csv folder and equipe a shapefile with the csv data. Is this the sort of thing you mean?

3
  • actually I am trying to convert a point based shape to someother thing using the point coordinates. I am trying to draw circles to selected points with the radius determined by user. So that I need the attributes of selected features and a radius field populated according to radius input stored in a list. I asked in another thread but had no answer for it, if you'd like I can share it.
    – nagellette
    Apr 14, 2014 at 12:29
  • So you have got a point layer with attributed data and you want to create a polygone layer, with shapes being drawn around each point at a radius specified in the attributes table? Apr 14, 2014 at 13:20
  • yes, you can see the code and the original question [here]. <gis.stackexchange.com/questions/92778/…>
    – nagellette
    Apr 14, 2014 at 13:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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