I'm using pyqtgraph to plot radar data (in 2D and 3D) using a GLViewWidget. Adding and visualizing the data in 2D and 3D works well.
I also added text labels using GLTextItem, but they are a bit mispositioned because I cannot retrieve the width of a GLTextItem
to take the text width into account when placing the label text (see the following screenshot -> apparently the anchor of a GLTextItem
is the bottom left corner):
My question is how to retrieve the size of a GLTextItem
?
The following code is used to generate the "angle labels" next to the individual segments:
def create_axes(self) -> None:
"""Create X, Y, Z axes for the 3D plot."""
# Angle labels
# Same idea as above: Use a vector and rotate it by the correct angle.
# Apparently, PyQtGraph does not allow to retrieve the bounding rectangle of a "GLTextItem".
# Therefore, hard-coded values for the offset correction must be used.
segment_angle_size_deg = 2 * self.azimuth_angle / self.azimuth_segments
for i in range(0, self.azimuth_segments + 1):
base_angle = 90 - self.azimuth_angle
angle_deg = base_angle + i * segment_angle_size_deg
# Extend the vector a bit to avoid that labels fall on the segment lines.
x_vector = (self.max_range + range_label_offset, 0)
x_pos, z_pos = self.rotate_vector_2d(x_vector, -np.deg2rad(angle_deg))
# -1 = correct to the left (in the right quadrants), 1 = correct to the right (in the left quadrants).
correction_direction = -1 if x_pos > 0 else 1
# Make the correction dependent on the current angle (i.e. at 90° no correction is necessary).
x_pos += range_label_offset * np.cos(np.deg2rad(angle_deg)) * correction_direction
angle_label = f"{abs(90 - angle_deg):.0f}"
angle_tick = gl.GLTextItem(
pos=(x_pos, 0, z_pos),
text=f"{angle_label}",
font=QFont("Helvetica", 10, QFont.Weight.ExtraLight),
color=self.grid_color,
)
# TODO: Retrieve the width of the text to correct its position.
self.gl_widget_items.append(angle_tick)
You can get the size in pixels using QFontMetrics with its method horizontalAdvance
.
I suggest putting the font type before calling GLTextItem
.
font = QFont("Helvetica", 10, QFont.Weight.ExtraLight)
metrics = QtGui.QFontMetrics(font)
text_width = metrics.horizontalAdvance(f"{angle_label}")