Widget's “destroyed” signal is not fired (PyQT)

前端 未结 2 727
Happy的楠姐
Happy的楠姐 2021-01-17 23:26

I have a widget which would have to do some manual cleanup after it\'s destroyed (stop some threads). However for some reason the \"destroyed\" signal of the widget is not f

2条回答
  •  臣服心动
    2021-01-17 23:59

    The python class instance (or at least the pyqt<->qt link) doesn't exist by the time destroyed is emitted. You can work around this by making the destroyed handler a staticmethod on the class. This way, the python method will still exist when the destroyed signal is emitted.

    class MyWidget(QWidget):
    
        def __init__(self, parent):
            super(MyWidget, self).__init__(parent)
            self.destroyed.connect(MyWidget._on_destroyed)
    
        @staticmethod
        def _on_destroyed():
            # Do stuff here
            pass
    

    If you need information specific to the class instance you can use functools.partial and the instance __dict__ to pass that info to the destruction method.

    from functools import partial
    
    class MyWidget(QWidget):
    
        def __init__(self, parent, arg1, arg2):
            super(MyWidget, self).__init__(parent)
            self.arg1 = arg1
            self.arg2 = arg2
            self.destroyed.connect(partial(MyWidget._on_destroyed, self.__dict__))
    
        @staticmethod
        def _on_destroyed(d):
            print d['arg1']
    

提交回复
热议问题