PyQt6:如何从QGraphicsScene获取鼠标位置并在其他类中使用
问题:PyQt6中QLabel实时显示QGraphicsScene鼠标坐标报错
错误原因
- 直接通过
Window.getPosition(Window, ...)用类调用实例方法,此时方法内的self指向Window类而非实例,类没有label属性,触发AttributeError。 getPosition方法中错误引用self.posX,实际应该使用传入的posX参数。- 硬编码调用其他类的方法不符合PyQt组件通信规范,应该用信号与槽机制实现解耦。
修正后的代码
import sys from PyQt6 import QtWidgets, QtCore from PyQt6.QtWidgets import QVBoxLayout, QWidget, QLabel class GraphicsScene(QtWidgets.QGraphicsScene): # 定义自定义信号,传递鼠标x坐标 mouseMoved = QtCore.pyqtSignal(float) def __init__(self, parent=None): super().__init__(parent) def mouseMoveEvent(self, event): super().mouseMoveEvent(event) # 保留父类原有事件处理逻辑 pos_x = event.scenePos().x() self.mouseMoved.emit(pos_x) # 发射坐标信号 class GraphicsView(QtWidgets.QGraphicsView): def __init__(self, parent=None): super().__init__(parent) self.setMouseTracking(True) self.scene = GraphicsScene(self) self.setScene(self.scene) class Window(QWidget): def __init__(self): super().__init__() self.layout = QVBoxLayout() self.gw = GraphicsView() self.layout.addWidget(self.gw) self.label = QLabel("Coordinate: x") self.layout.addWidget(self.label) self.setLayout(self.layout) # 连接信号与槽:场景鼠标移动信号 -> 更新标签的槽函数 self.gw.scene.mouseMoved.connect(self.updateCoordinate) def updateCoordinate(self, pos_x): self.label.setText(f"Coordinate: x = {pos_x:.2f}") # QLabel更新文本后会自动刷新,无需手动调用repaint print(pos_x) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) w = Window() w.show() sys.exit(app.exec())
关键改动说明
- 给
GraphicsScene添加mouseMoved自定义信号,鼠标移动时发射当前x坐标,实现组件间解耦通信。 - 在
Window初始化方法中,将场景的信号与更新标签的槽函数连接,完成坐标传递逻辑。 - 修正变量命名为小写
layout,符合Python命名规范。 - 在
mouseMoveEvent中调用父类方法,确保原有事件逻辑正常执行。
内容的提问来源于stack exchange,提问作者nonoY
相关产品推荐
相关产品推荐

