Bug report #18781

Updated by Jürgen Fischer almost 6 years ago

The next code only works on 2.xx versions of QGIS, returning empty list when it should export Polylines coordinates like in QGIS 2.xx

<pre>
def getAttributeIndex(aLayer, attrName):
if len(attrName) > 10 and aLayer.storageType() == 'ESRI Shapefile':
iface.messageBar().pushMessage('Error', 'For ESRI Shapefiles, the maximum length of any attribute name is 10. Please choose a shorter attribute name.', level=QgsMessageBar.CRITICAL)
return -3
AttrIdx = aLayer.dataProvider().fieldNameIndex(attrName)
if AttrIdx == -1:
caps = aLayer.dataProvider().capabilities()
if caps & QgsVectorDataProvider.AddAttributes:
res = aLayer.dataProvider().addAttributes([QgsField(attrName, QVariant.String)])
AttrIdx = aLayer.dataProvider().fieldNameIndex(attrName)
aLayer.updateFields()
if AttrIdx == -1:
iface.messageBar().pushMessage('Error', 'Failed to create attribute!', level=QgsMessageBar.CRITICAL)
return -1
else:
iface.messageBar().pushMessage('Error', 'Failed to add attribute!', level=QgsMessageBar.CRITICAL)
return -1
return AttrIdx

layer_name= 'L_MT_IND'
#layerMT1=QgsMapLayerRegistry.instance().mapLayersByName(layer_name)[0] ## for QGIS 2
layerMT1=QgsProject.instance().mapLayersByName(layer_name)[0] ## for QGIS 3
idx = getAttributeIndex(layerMT1, "DSSName")

lineasMT = layerMT1.getFeatures()
for lineaMT in lineasMT:
line = lineaMT.geometry().asPolyline()
# Read line geometry
print(line)
</pre>

Back