如何确保 QApplication 和其 QThread 都已关闭

5 阅读1分钟

如何确保 QApplication 及其 QThreads 都已关闭?以下代码创建了一个 QDialog,该 QDialog 会启动一个 QThread,该 QThread 会获取一个时间很长的函数进行计算。QDialog 的 closeEvent() 方法被修改为终止启动的线程,如何确保仅在该线程完成其正在执行的任务后才终止该线程?线程的 quit() 和 terminate() 方法之间有什么区别?主应用程序窗口关闭后是否应始终终止该线程?为什么在 Mac OS X 上,即使已关闭主对话框并终止该线程,Python 进程仍列在活动监视器中?

import threading
import Queue as Queue
import datetime

global queue
queue = Queue.Queue()


class Thread(QThread):
    def __init__(self, queue, parent):
        QThread.__init__(self, parent)
        self.queue = queue

    def run(self):
        while True:
            task = queue.get()
            output = task()
            queue.task_done()


def longToCalculate():
    for i in range(30000000):
        i += i
        if not i % 100000:
            print('%s ...still calculating ' % datetime.datetime.now())
    print('calculation completed')
    return i


class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

    def closeEvent(self, event):
        # self.thread.quit()
        self.thread.terminate()
        event.accept()


class Dialog(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.queue = Queue.Queue()
        self.thread = Thread(queue=self.queue, parent=self)
        self.thread.start()
        queue.put(longToCalculate)

if __name__ == '__main__':
    app = QApplication([])
    dialog = Dialog()
    dialog.show()
    qApp.exec_()

2、解决方案:

这里有一个示例代码,不包含 Queue。

import os, sys
import datetime

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class Thread( QThread ):
    def __init__( self, parent ):

        QThread.__init__( self, parent )

    def run( self ):
        self.longToCalculate()

    def longToCalculate( self ):
        for i in range( 30000000 ):
            i += i

            if ( i % 1000000 == 0 ):
                print( '%s ...still calculating' % QDateTime.currentDateTime().toString() )

        print( 'calculation completed' )
        return i

class Dialog(QDialog):
    def __init__( self, parent = None ):

        QDialog.__init__( self, parent )

        self.thread = Thread( parent = self )
        self.thread.start()

        self.thread.finished.connect( self.threadComplete )

    def threadComplete( self ) :
        QMessageBox.information( self, "Thread complete", "The thread has finished running. This program wil automatically close now." )
        self.close()

    def closeEvent( self, cEvent ) :

        if self.thread.isRunning() :
            QMessageBox.information( self, "Thread running", "The thread is running. You cannot close this program." )
            cEvent.ignore()

        else :
            cEvent.accept()

if __name__ == '__main__':

    app = QApplication( sys.argv )

    dialog = Dialog()
    dialog.show()

    qApp.exec_()