2
def initGui(self):
    """Create the menu entries and toolbar icons inside the QGIS GUI."""

    icon_path = ':/plugins/cropEt/icon.png'
    self.add_action(
        icon_path,
        text=self.tr(u'links crop et'),
        callback=self.run,
        parent=self.iface.mainWindow())

     # connect our select function to the canvasClicked signal
    result = self.clickTool.canvasClicked.connect(self.selectFeature)
    QMessageBox.information( self.iface.mainWindow(),"Info", "connect = %s"%str(result) )


def unload(self):
    """Removes the plugin menu item and icon from QGIS GUI."""
    for action in self.actions:
        self.iface.removePluginMenu(
            self.tr(u'&Testlink'),
            action)
        self.iface.removeToolBarIcon(action)
    # remove the toolbar
    del self.toolbar

def handleMouseDown(self, point, button):
    #QMessageBox.information( self.iface.mainWindow(),"Info", "X,Y = %s,%s" % (str(point.x()),str(point.y())) )
    self.dlg.clearTextBrowser()
    self.dlg.setTextBrowser( str(point.x()) + " , " +str(point.y()) )


def selectFeature(self, point, button):
    layer = self.iface.addVectorLayer("D:/python/cropped_area.shp", "sample_cropped area","ogr")
    selectList = []
    if layer:
        for feature in layer.getFeatures():
            # fetch geometry
                geom = feature.geometry()
                print "Feature ID %d: " % feature.id()
                layer.setSelectedFeatures(selectList)
           # show some information about the feature
            #if geom.type() == QGis.Point:
                #x = geom.asPoint()
                #print "Point: " + str(x)
            #elif geom.type() == QGis.Line:
             #   x = geom.asPolyline()
              #  print "Line: %d points" % len(x)
                #if geom.type() == QGis.Polygon:
                    #x = geom.asPolygon()
                    #numPts = 0
                #for ring in x:
                    #numPts += len(ring)
                    #print "Polygon: %d rings with %d points" % (len(x), numPts)
                #else:
                    #print "Unknown"

            # fetch attributes
                attrs = feature.attributes()
                #if attrs==row[0].strip():
                #selection.append(feature.id())
   # attrs is a list. It contains all the attribute values of this feature
                print attrs
                #layer.setSelectedFeatures(selection)
    if not layer:
        print "Layer failed to load!" 

    QMessageBox.information( self.iface.mainWindow(),"Info", "Click on the feature to select" )


    #else:
           # QMessageBox.information( self.iface.mainWindow(),"Info", "No layer currently selected in TOC" )

I want to load a shapefile and want to display the properties like feature count, attribute table list in QGIS interface plugin. Accordingly wrote the code; a portion is attached... But, on each mouse click, a new layer is getting created and no feature property is displayed even after removing the commented statements.

Can anyone suggest the error?

3

The mistake is in this line:

layer = self.iface.addVectorLayer("D:/python/cropped_area.shp", "sample_cropped area","ogr")

The layer is added anew each time selectFeature is fired.

You'd rather want to add the layer once (e.g. in the __init__ or initGui function), and save it to a member of your plugin object (e.g. self.layer=addVectorLayer(…)) so you can refer to it in selectFeature.

The whole code might look similar to this:

def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI."""

    icon_path = ':/plugins/cropEt/icon.png'
    self.add_action(
        icon_path,
        text=self.tr(u'links crop et'),
        callback=self.run,
        parent=self.iface.mainWindow())


    # LOAD YOUR LAYER HERE
    self.layer=self.iface.addVectorLayer("D:/python/cropped_area.shp", "sample_cropped area","ogr")


    # connect our select function to the canvasClicked signal
    result = self.clickTool.canvasClicked.connect(self.selectFeature)
    QMessageBox.information( self.iface.mainWindow(),"Info", "connect = %s"%str(result) )


def unload(self):
    """Removes the plugin menu item and icon from QGIS GUI."""
    for action in self.actions:
        self.iface.removePluginMenu(
            self.tr(u'&Testlink'),
            action)
        self.iface.removeToolBarIcon(action)
    # remove the toolbar
    del self.toolbar

def handleMouseDown(self, point, button):
    #QMessageBox.information( self.iface.mainWindow(),"Info", "X,Y = %s,%s" % (str(point.x()),str(point.y())) )
    self.dlg.clearTextBrowser()
    self.dlg.setTextBrowser( str(point.x()) + " , " +str(point.y()) )


def selectFeature(self, point, button):
    layer = self.layer # USE THE STORED REFERENCE TO YOUR LAYER HERE
    selectList = []
    if layer:
        for feature in layer.getFeatures():
            # fetch geometry
                geom = feature.geometry()
                print "Feature ID %d: " % feature.id()
                layer.setSelectedFeatures(selectList)
           # show some information about the feature
            #if geom.type() == QGis.Point:
                #x = geom.asPoint()
                #print "Point: " + str(x)
            #elif geom.type() == QGis.Line:
             #   x = geom.asPolyline()
              #  print "Line: %d points" % len(x)
                #if geom.type() == QGis.Polygon:
                    #x = geom.asPolygon()
                    #numPts = 0
                #for ring in x:
                    #numPts += len(ring)
                    #print "Polygon: %d rings with %d points" % (len(x), numPts)
                #else:
                    #print "Unknown"

            # fetch attributes
                attrs = feature.attributes()
                #if attrs==row[0].strip():
                #selection.append(feature.id())
   # attrs is a list. It contains all the attribute values of this feature
                print attrs
                #layer.setSelectedFeatures(selection)
    if not layer:
        print "Layer failed to load!" 

    QMessageBox.information( self.iface.mainWindow(),"Info", "Click on the feature to select" )


    #else:
           # QMessageBox.information( self.iface.mainWindow(),"Info", "No layer currently selected in TOC" )
  • Thank you @christoph ..It worked as expected. Now, the problem is how to select a particular feature within the polygon with a single click.Any idea? – Drisya Jayakumar Jul 15 '15 at 11:53
  • Yes, as a matter of fact: in selectFeature you call layer.setSelectedFeatures(selectList) while selectList is an empty list … I can't tell from your code exactly what the values of the function arguments pointand button would be, but you'd have to do something along the lines of: if geom.intersects(point): selectList.append(feature); (<qgis.org/api/2.8/classQgsGeometry.html>). (possibly before that projecting the point to the layers reference system) – christoph Jul 15 '15 at 15:12

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.