2

I am a new for QGIS, working in Python.

I add a buildings(.shp) vector layer into QGIS, just like this:

enter image description here

I'd like to get the geometrys of some features, then I can do analysis on the center point.

But when I use API geometry(), it returns me a empty geometry and I cannot get the center point. When I tried .hasGeometry(), it returns me a False.

My code is following:

path = '/Users/vctcn93/Desktop/export/canton.shp'

def SelectRange(px1, py1, px2, py2):

    layer = qgis.utils.iface.activeLayer()

    p1 = QgsPointXY(px1, py1)
    p2 = QgsPointXY(px2, py2)
    rec = QgsRectangle(p1,p2)

    layer.selectByRect(rec, 0)

    ids = layer.selectedFeatureIds()
    features = [QgsFeature(id) for id in ids]

    return features, rec, layer
    #retruns list<QgsFeature>,QgisRectangle,QgisVectorLayer 

def SelectFea(features, rectangle):
    for a in features:
        geometry = a.geometry()#here returns me a empty geometry
        bbx = geometry.boundingBox()

        if bbx.xMaximum() >= rectangle.xMaximum() \
        or bbx.yMinimum() <= rectangle.yMinimum():
            features.remove(a)

    return features

Please help me on this problem, I tried a lot but cannot figure out.

1

Try using getSelectedFeatures:

Returns an iterator of the selected features.

Example:

layer = iface.activeLayer()
layer.selectByRect(QgsRectangle(QgsPointXY(405265,6457186),QgsPointXY(409286,6463306)))
features = [f for f in layer.getSelectedFeatures()]

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.