I'm trying to make a function like ArcGIS's select using Python 3.6 , QGIS 2.8.6 and QtDesigner, so this is my code:
def execute(self):
layers = self.iface.legendInterface().layers()
selectedLayerIndex = self.dlg.layers.currentText()
layer=None
for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
if lyr.name() == selectedLayerIndex:
layer = lyr
qgis.utils.iface.setActiveLayer(layer)
expr = QgsExpression(" \"BORONAME\" = 'The Bronx'")
it = layer.getFeatures( QgsFeatureRequest( expr ) )
ids = [i.id() for i in it]
layer.setSelectedFeatures( ids )
self.dlg.expression.setText(" ")
self.dlg.lineEdit.setText(" ")
break
I'm choosing a layer that has an attribute called "BORONAME" with the value 'The Bronx' when I try the code on Python console plugin it works fine, the results shown selected, but I got nothing when I use the plugin that I created.
Vince
20.5k16 gold badges49 silver badges65 bronze badges
asked May 29, 2019 at 1:52
-
Please consider to port this directly to QGIS 3. QGIS 2 is not so much supported anymore.Riccardo– Riccardo2019年05月29日 04:50:50 +00:00Commented May 29, 2019 at 4:50
-
It looks ok to me. Try to put some print messages into the execute function and then check if that statement pops out in QGIS python console. Then you know if that code is executed from plugin.DavidP– DavidP2019年05月29日 05:07:29 +00:00Commented May 29, 2019 at 5:07
1 Answer 1
i just had to turn the 'break' to the if level
layers = self.iface.legendInterface().layers()
selectedLayerIndex = self.dlg.layers.currentText()
layer=None
for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
lyr.removeSelection()
if lyr.name() == selectedLayerIndex:
layer = lyr
expression =str(" \"BORONAME\" = 'The Bronx'")
expr = QgsExpression(expression)
it = layer.getFeatures( QgsFeatureRequest( expr ) )
layer.setSelectedFeatures( ids )
self.dlg.expression.setText(" ")
self.dlg.lineEdit.setText(" ")
self.iface.mapCanvas().zoomToSelected()
break
answered May 30, 2019 at 1:22
lang-py