我正在使用 pyqtgraph 使用 GLViewWidget 绘制雷达数据(2D 和 3D)。添加和可视化 2D 和 3D 数据效果很好。
我还使用 GLTextItem 添加了文本标签,但它们的位置有点错误,因为我无法检索
GLTextItem
的宽度以在放置标签文本时考虑文本宽度(请参见下面的屏幕截图 -> 显然是锚点) GLTextItem
是左下角):
我的问题是如何检索
GLTextItem
的大小?
以下代码用于生成各个线段旁边的“角度标签”:
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)
您可以使用 QFontMetrics 及其方法
horizontalAdvance
获取像素大小。
我建议在调用之前输入字体类型GLTextItem
。
font = QFont("Helvetica", 10, QFont.Weight.ExtraLight)
metrics = QtGui.QFontMetrics(font)
text_width = metrics.horizontalAdvance(f"{angle_label}")