6

We need to get LabelGeometry from a feature. There is such a class QgsLabelPosition, it sets parameters. I need to get the parameters of the bounding box label.

enter image description here

Version QGIS 3.16.4

0

3 Answers 3

3

You need the labelRect attribute. My way of getting the value of the labelReсt attribute is as follows.

Take a point that intersects with some label(s). In my case, this point is the last position of the mouse cursor:

point = iface.mapCanvas().mouseLastXY()
point = iface.mapCanvas().getCoordinateTransform().toMapCoordinates(point)

Since several labels can intersect with our point at once, labelsAtPosition returns a list of QgsLabelPosition objects:

labels = iface.mapCanvas().labelingResults().labelsAtPosition(QgsPointXY(point))

Get the attributes we need (for example, LabelRect) of each QgsLabelPosition object (of each label).

for l in labels:
    print(l.labelRect)

In the same way, we can get all other QgsLabelPosition attributes: cornerPoints, featureId, height, isDiagram, isPinned, isUnplaced, labelFont, labelGeometry, labelRect, labelText, layerID, providerID, rotation, upsideDown, width.

2

Add 2 fields to the featureclass: label_x,label_y (Type: real) and set the placement in the label options to those fields:

enter image description here

Do NOT check the "Store Data in the project" option!

layer=QgsProject.instance().mapLayersByName('xxx')[0]
for feat in layer.getSelectedFeatures():
    x=feat['label_x']
    y=feat['label_y']
    p1=QgsPointXY(x,y)
    buffer=1
    rec=QgsRectangle.fromCenterAndSize(p1,buffer,buffer)
    labels=iface.mapCanvas().labelingResults ().labelsWithinRect(rec)
    if len(labels)>0:
        label_rec=labels[0].labelRect
        print(label_rec)

Tested in QGIS 3.16.10

1

This will return all label geometries of the labels in current map extent:

extent = iface.mapCanvas().extent()
labelresults = iface.mapCanvas().labelingResults()
labelsinextent = labelresults.labelsWithinRect(extent) #Find the labels in current map extent

for lbl in labelsinextent:
    h = lbl.height
    w = lbl.width
    labelrect = lbl.labelRect
    labelgeom = lbl.labelGeometry

#labelrect
#<QgsRectangle: 527101.23714807606302202 6882549.52799519244581461, 527175.66743653104640543 6882609.07222595624625683>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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