How to make sure the QApplication and its QThreads are all closed

alphanumeric

The code below creates a single QDialog which starts a QThread that gets a function that is long to calculate. QDialog's closeEvent() method was modified to terminate the thread that was started.

How to make sure the thread is terminated only if it completed a task it was working on? What is the difference between stopping a thread with its quit() and its terminate() method? Should the thread always be terminated before the main application window is closed? Why on Mac OS X the Python process remains to be listed in Activity Monitor even after the main dialog is closed and the thread is terminated?

enter image description here

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_()
Marcus

Here is a sample code which does not include 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_()

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to resolve "could not create/delete. make sure all files from that directory are closed"

From Dev

how to make sure all promises are resolved in javascript?

From Dev

How to make this accordion load with all menus closed?

From Dev

In Qt, find out that all windows are closed, when QApplication::processEvents() is used?

From Dev

make sure graphics device gets closed

From Dev

How do I make sure a file opened by URLLoader is closed so I can write on it with a FileStrewam

From Dev

How can i make sure that if i closed the program and run again it will create the new file in a new directory?

From Java

How to check to make sure all items in a list are of a certain type

From Dev

How can I make sure AuthName works in all browsers?

From Dev

Angular directive: how to make sure all nested templates and partials loaded?

From Dev

How to make sure all sql queries run without error?

From Dev

How to make sure all components are deselected when using /COMPONENTSONLYONCUSTOM?

From Dev

How to make sure an element is on top of all other elements in a page?

From Dev

How to make sure Aether 'downloads' all dependencies in your local repo?

From Dev

Angular directive: how to make sure all nested templates and partials loaded?

From Dev

How to make sure Observable stream handles all requests

From Dev

Tensorflow: how to make sure all samples in each batch are with different labels?

From Dev

how to resolve ignitecheckedexception: make sure all objects in cache configuration are serializable

From Dev

How to make sure app restarts each time its opened even if its just put in background? android

From Dev

How to correctly Dispose of a plugin making sure all open service calls are closed

From Dev

How to make sure every data members of a class have been copied in its copy constructor?

From Dev

What actually the 'socket' object is in socket.io? How to make sure its usage is optimum?

From Dev

How to make sure that a inner div does not go outside its container div flexbox with CSS/HTML only?

From Dev

How do I make sure that the domain is up and the CLI is connected to its controller?

From Dev

How make sure that a Composite also lays out its children after calling Composite.layout() in Java

From Dev

What to use to make sure a connection pool always gets closed?

From Dev

Does Spring make sure Closeable beans are closed in the correct order?

From Dev

Python : how to make subclasses 'closed' under methods inherited from its superclass

From Dev

Python : how to make subclasses 'closed' under methods inherited from its superclass

Related Related

  1. 1

    How to resolve "could not create/delete. make sure all files from that directory are closed"

  2. 2

    how to make sure all promises are resolved in javascript?

  3. 3

    How to make this accordion load with all menus closed?

  4. 4

    In Qt, find out that all windows are closed, when QApplication::processEvents() is used?

  5. 5

    make sure graphics device gets closed

  6. 6

    How do I make sure a file opened by URLLoader is closed so I can write on it with a FileStrewam

  7. 7

    How can i make sure that if i closed the program and run again it will create the new file in a new directory?

  8. 8

    How to check to make sure all items in a list are of a certain type

  9. 9

    How can I make sure AuthName works in all browsers?

  10. 10

    Angular directive: how to make sure all nested templates and partials loaded?

  11. 11

    How to make sure all sql queries run without error?

  12. 12

    How to make sure all components are deselected when using /COMPONENTSONLYONCUSTOM?

  13. 13

    How to make sure an element is on top of all other elements in a page?

  14. 14

    How to make sure Aether 'downloads' all dependencies in your local repo?

  15. 15

    Angular directive: how to make sure all nested templates and partials loaded?

  16. 16

    How to make sure Observable stream handles all requests

  17. 17

    Tensorflow: how to make sure all samples in each batch are with different labels?

  18. 18

    how to resolve ignitecheckedexception: make sure all objects in cache configuration are serializable

  19. 19

    How to make sure app restarts each time its opened even if its just put in background? android

  20. 20

    How to correctly Dispose of a plugin making sure all open service calls are closed

  21. 21

    How to make sure every data members of a class have been copied in its copy constructor?

  22. 22

    What actually the 'socket' object is in socket.io? How to make sure its usage is optimum?

  23. 23

    How to make sure that a inner div does not go outside its container div flexbox with CSS/HTML only?

  24. 24

    How do I make sure that the domain is up and the CLI is connected to its controller?

  25. 25

    How make sure that a Composite also lays out its children after calling Composite.layout() in Java

  26. 26

    What to use to make sure a connection pool always gets closed?

  27. 27

    Does Spring make sure Closeable beans are closed in the correct order?

  28. 28

    Python : how to make subclasses 'closed' under methods inherited from its superclass

  29. 29

    Python : how to make subclasses 'closed' under methods inherited from its superclass

HotTag

Archive