Geographic Information Systems Asked by Christian Golth on December 14, 2020
I have got this code in PyQGIS to to save a selected feature into a variable.
class selectTool(QgsMapToolIdentifyFeature):
def __init__(self, iface):
self.iface = iface
self.canvas = self.iface.mapCanvas()
self.layer = self.iface.activeLayer()
QgsMapToolIdentifyFeature.__init__(self, self.canvas, self.layer)
self.iface.currentLayerChanged.connect(self.active_changed)
def active_changed(self, layer):
self.layer.removeSelection()
if isinstance(layer, QgsVectorLayer) and layer.isSpatial():
self.layer = layer
self.setLayer(self.layer)
def canvasPressEvent(self, event):
found_feature = self.identify(event.x(), event.y(), [self.layer], QgsMapToolIdentify.LayerSelection)
self.layer.selectByIds([f.mFeature.id() for f in found_feature])
print (type(found_feature))
print (found_feature)
def deactivate(self):
self.layer.removeSelection()
t = selectTool(iface)
iface.mapCanvas().setMapTool(t)
This is working so far. Just the print
statement… print (found_feature)
… gives me:
[<qgis._gui.QgsMapToolIdentify.IdentifyResult object at 0x000001E2669BDDC8>]
My question is now: how can I print the features and values which are inside the created list? I guess I somehow have to make it accessible?
I am very new to PyQGIS and also Python.
In your case, since you clicked on one feature, the list has one item. In any case, found_feature
gives all IdentifyResult
instances and IdentifyResult.mFeature
gives the feature.
If you want to print all features and attributes, change canvasPressEvent
like this:
def canvasPressEvent(self, event):
found_feature = self.identify(event.x(), event.y(), [self.layer], QgsMapToolIdentify.LayerSelection)
self.layer.selectByIds([f.mFeature.id() for f in found_feature])
identified_features = [f.mFeature for f in found_feature]
for f in identified_features:
print(f.id())
print(f.attributes())
Correct answer by Kadir Şahbaz on December 14, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP