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