当我在python和pyqt中关闭app时,没有运行类析构函数

mas*_*ood 2 python multithreading pyqt

当我退出程序(sys.exit(app.exec _()))时,主窗体关闭,但有两个问题:
1 - MainForm类的析构
函数不运行2 -
当我关闭app时,线程仍在运行,MainForm的析构函数被破坏,所有线程也被杀死

    class MainForm(QMainWindow,Ui_MainWindow):
        def __init__(self,parent=None):
            super(MainForm,self).__init__(parent)
            self.setupUi(self)
            #...
        def init_main_form(self):
            #...
            self.show_time()
        def show_time(self):
            self.label_9.setText(u"{}:{}:{}".format(str(datetime.datetime.now().hour),str(datetime.datetime.now().minute),str(datetime.datetime.now().second)))
            self.label_9.resize(self.label_9.width()+len(self.label_9.text())*3,self.label_9.height())
            b = threading.Timer(1,self.show_time)
            #b.setName('localtime')
            #self.thread_list.append(b)
            b.start()
        def __del__(self):
            print("app is closed")
            for tr in threading.enumerate():
                if tr.isAlive():
                    tr._Thread__stop()
                    # or tr.finished
                    # or tr.terminate()
    def main():
        app = QApplication(sys.argv)
        main_form = MainForm()
        main_form.show()
        sys.exit(app.exec_())

    if __name__ == '__main__':
        main()
Run Code Online (Sandbox Code Playgroud)

Jak*_*ube 5

我不确定为什么不调用析构函数。但至少以下应该有效。

每当用户尝试关闭窗口时,closeEvent都会调用该方法。所以如果你想在关闭之前做一些事情,甚至阻止用户退出,你只需实现这个方法。

class MainForm(QMainWindow,Ui_MainWindow):
    # lots of methods

    def closeEvent(self, event):
        # here you can terminate your threads and do other stuff

        # and afterwards call the closeEvent of the super-class
        super(QMainWindow, self).closeEvent(event)
Run Code Online (Sandbox Code Playgroud)


Kar*_*wak 5

当你在它时,请记住,当解释器退出时,不保证每个文档 __del__都能运行.

__del__在其他Python实现中更为棘手(如Jython).您的应用程序不应该依赖它执行才能正常运行.