PyQt(Python+Qt)学习随笔:自定义信号在emit发射信号时报错:AttributeError: object has no attribute
如果使用自定义信号,一定要记得信号是类变量,必须在类中定义,不能在实例方法中定义,否则后面发射信号和连接槽方法时都会报错。
案例:
class configWin(ui_configWin.Ui_configWin,QtWidgets.QWidget):
def __init__(self,parent=None):
super().__init__(parent)
self.setupUi(self)
sizeChanged = QtCore.pyqtSignal(int)
def resize(self,width,height):
self.sizeChanged.emit(width)
print("sizeChanged....")
super().resize(width,height)
结果执行时报错:
AttributeError: ‘configWin’ object has no attribute ‘sizeChanged’
正确的做法应该是:
class configWin(ui_configWin.Ui_configWin,QtWidgets.QWidget):
sizeChanged = QtCore.pyqtSignal(int)
def __init__(self,parent=None):
super().__init__(parent)
self.setupUi(self)
def resize(self,width,height):
self.sizeChanged.emit(width)
super().resize(width,height)
更多自定义信号的内容请参考《第15.19节 PyQt(Python+Qt)入门学习:自定义信号与槽连接》。