2

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.

  • Please consider to port this directly to QGIS 3. QGIS 2 is not so much supported anymore. – Riccardo May 29 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 May 29 at 5:07
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    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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