PyQt5中QPushButton点击事件无法关联类内函数的问题与解决
问题原因与解决方案
为什么初始代码点击无反应?
你的MyButton不是Qt的QObject子类,在Window的__init__里创建的button = MyButton(parent=self)是局部变量,当__init__执行完毕后,Python垃圾回收器会回收这个MyButton实例。此时QPushButton的clicked信号关联的print_hello_world方法已不存在,所以点击按钮没有任何反应。
为什么添加button.push_button.clicked.connect(lambda:button)后生效?
这行代码中的lambda表达式持有了button的引用,相当于给MyButton实例增加了引用计数,垃圾回收器不会再回收它,实例得以保留,信号触发时print_hello_world方法就能正常被调用。
仅修改MyButton类的解决方法
有两种可行的修改方式,都能让原代码正常运行:
方式1:让MyButton继承QObject
借助Qt的父子对象管理机制,当给MyButton设置父对象后,Qt会自动维护其生命周期,避免被Python垃圾回收器随意回收。修改后的代码如下:
import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import QObject class MyButton(QObject): def __init__(self, parent): super().__init__(parent) self.parent = parent self.push_button = QPushButton('Print', parent) self.push_button.clicked.connect(self.print_hello_world) def print_hello_world(self): print("Hello World") class Window(QMainWindow): def __init__(self): QMainWindow.__init__(self) button = MyButton(parent=self) App = QApplication(sys.argv) window = Window() window.show() sys.exit(App.exec())
方式2:让MyButton直接继承QPushButton
这种方式更符合Qt控件封装的逻辑,直接将自定义类作为QPushButton的子类,无需额外维护内部的QPushButton实例:
import sys from PyQt5.QtWidgets import * class MyButton(QPushButton): def __init__(self, parent): super().__init__('Print', parent) self.clicked.connect(self.print_hello_world) def print_hello_world(self): print("Hello World") class Window(QMainWindow): def __init__(self): QMainWindow.__init__(self) button = MyButton(parent=self) App = QApplication(sys.argv) window = Window() window.show() sys.exit(App.exec())
内容的提问来源于stack exchange,提问作者SMR
相关产品推荐
相关产品推荐

