Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python和pyqt中关闭应用程序时未运行类析构函数_Python_Multithreading_Pyqt - Fatal编程技术网

在python和pyqt中关闭应用程序时未运行类析构函数

在python和pyqt中关闭应用程序时未运行类析构函数,python,multithreading,pyqt,Python,Multithreading,Pyqt,当我退出程序(sys.exit(app.exec_())时,主窗体关闭,但有两个问题: 1-MainForm类的析构函数未运行 2-线程仍在运行 我想当我关闭应用程序时,MainForm的析构函数会运行,所有线程也会被杀死 class MainForm(QMainWindow,Ui_MainWindow): def __init__(self,parent=None): super(MainForm,self).__init__(parent)

当我退出程序(sys.exit(app.exec_())时,主窗体关闭,但有两个问题:
1-MainForm类的析构函数未运行
2-线程仍在运行
我想当我关闭应用程序时,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()

我不知道为什么不调用析构函数。但至少以下几点应该有效

每当用户试图关闭窗口时,就会调用
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)

当您使用时,请记住当解释器退出时,
\uuu del\uu
不保证运行


\uuu del\uu
在Python的其他实现(如Jython)中更为棘手。您的应用程序不应该依赖于它的执行来正确运行。

是的,它工作正常。如果您说问题1的解决方案也很好。谢谢