PyQT中MyPlotWidget类无法发射信号问题求助
问题排查与修复方案
错误点1:窗口类继承初始化错误
another类继承自QtWidgets.QMainWindow,但初始化时错误调用了未定义的MainWindow作为父类参数,会直接导致窗口初始化失败,控件无法正常工作。
修复:
class another(QtWidgets.QMainWindow): def __init__(self, parent=None): super(another, self).__init__(parent) # 改为当前类名 self.plot = MyPlotWidget() self.setCentralWidget(self.plot) # 将plot添加到窗口,确保能接收事件 self.graph = MyGraph() self.plot.myplotSignal.connect(self.graph.test)
错误点2:MyGraph类未继承QObject
PyQt的槽函数依赖QObject元对象系统,MyGraph未继承QtCore.QObject,@pyqtSlot装饰器无法生效,信号连接会直接失败。
修复:
class MyGraph(QtCore.QObject): # 必须继承QObject def __init__(self, parent=None): super().__init__(parent) # 初始化父类 @QtCore.pyqtSlot(int) def test(self,signal): print("signal accepted")
错误点3:未定义的plotDialog对象
mouse_clicked方法中直接使用plotDialog,但代码中没有定义或实例化该对象,会抛出NameError,导致函数执行中断,无法走到emit信号的步骤。
修复:
若暂不需要该逻辑,先注释掉相关代码保证函数执行完整;若需要则先实例化plotDialog并确保id_list存在:
def mouse_clicked(self, mouseClickEvent): self.signal = id(self) # 先注释或修复plotDialog相关代码 # plotDialog.plotIndex = plotDialog.id_list.index(self.signal) self.myplotSignal.emit(self.signal)
错误点4:控件未添加到窗口
即使创建了MyPlotWidget,如果没有将其添加到窗口布局或设置为中心部件,控件不会显示也无法接收鼠标事件,导致sigMouseClicked信号无法触发。
修复:
在another类的__init__中添加:
self.setCentralWidget(self.plot)
可选:改用重写mousePressEvent捕获点击
如果scene().sigMouseClicked仍无法触发,可直接重写MyPlotWidget的鼠标事件方法,更可靠:
class MyPlotWidget(pg.PlotWidget): myplotSignal = QtCore.pyqtSignal(int) def __init__(self): super().__init__() def mousePressEvent(self, event): super().mousePressEvent(event) # 保留父类原有功能 self.signal = id(self) self.myplotSignal.emit(self.signal)
内容的提问来源于stack exchange,提问作者koreancoder
相关产品推荐
相关产品推荐

