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.
Version QGIS 3.16.4
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It only takes a minute to sign up.
Sign up to join this communityWe 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.
Version QGIS 3.16.4
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.
Add 2 fields to the featureclass: label_x,label_y (Type: real) and set the placement in the label options to those fields:
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
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>