What's wrong with running a pyQt thread from a python thread (not main)?

I had a python script console where I wanted to add a basic status window, so not knowing about pyqt I added a window. If I started pyqt from my main thread, it blocked everything else, so I started it from another thread. It worked fine for a few months, but I only noticed a warning (not sure how I missed it before): WARNING: QApplication was not created in the main() thread.

I'm wondering what kind of problems might arise.

This is a minified version of the code I am using by simply updating the window title:

from PyQt4 import QtGui, QtCore
import threading
import sys
from time import sleep

class MainWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MainWidget, self).__init__(parent)
        self.setWindowTitle(statusLine)
        self.timer = QtCore.QBasicTimer()
        self.timer.start(500, self)


    def updateWindow(self):
        self.setWindowTitle(statusLine)


    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():
            self.updateWindow()
        else:
            super(MainWidget, self).timerEvent(event)


def startWindow():
    app = QtGui.QApplication(sys.argv)
    mw = MainWidget()
    mw.show()
    app.exec_()


if __name__ == '__main__':
    global statusLine
    statusLine = 'foo'
    threadWindow = threading.Thread(target=startWindow)
    threadWindow.start()
    sleep(2)  # process lots of data
    statusLine = 'bar'
    # keep doing stuff and updating statusLine

      

Edit: I don't seem to get an alert with this simplified sample; instead, I only seem to get it if I run several other python threads before the one that runs pyQt. However, the question still remains: what is wrong with this?

+3


source to share


1 answer


I would say that since users interact with the GUI, there is a definite danger of people killing the GUI without actually killing the main program, this could lead to:

  • Problems starting another instance leading to resource leaks, conflicts, etc. &
  • Problems as it __main__

    tries to update a GUI that no longer exists.


It is generally believed that programs with graphical interfaces, be it QT or WX, have a GUI like __main__

, and have child threads that perform any background, computationally intensive processing. Of course, it's still a very good idea to explicitly kill any child threads in the OnExit method.

+4


source







All Articles