0

I have written a simple code of python GUI for sleeping my code for 10 seconds. At the same time, the GUI should run without freezing. Is not possible by defining primari thready and secondary thread? While I click on "Run" button pythonw.exe has stopped working. Does anyone have any thoughts on how I may be able to troubleshoot this? Thank you.

    import sys, threading
    from PyQt4 import QtGui, QtCore
    from PyQt4.QtCore import pyqtSlot
    from PyQt4.QtGui import *

    class Window(QtGui.QMainWindow):
        def __init__(self):
            super(Window,self).__init__()
            self.setGeometry(400,150, 550, 500)
            self.setWindowTitle("my first program")
            self.home()

        def home(self):
            self.button_1 = QtGui.QPushButton('Run', self)
            self.button_1.resize(60,25)
            self.button_1.move(230,230)
            self.button_1.clicked.connect(self.Thread_test)

            self.textbox_1 = QTextEdit(self)
            self.textbox_1.move(15,290)
            self.textbox_1.resize(510,170)

            self.show()

        def Thread_test(self):
            t = threading.Thread(target=self.calculation)
            t.start()

        def calculation(self):
            msg="program is working"
            self.textbox_1.setText(msg)
            time.sleep(5)
            msg="program was slept for few sec."
            self.textbox_1.setText(msg)

    def run():
        app=QtGui.QApplication(sys.argv)
        GUI=Window()
        sys.exit(app.exec_())    
    run()

1 Answers1

0

Qt Widgets are not thread safe. You should access a widget only from the thread that created it. See http://doc.qt.io/qt-5/thread-basics.html:

All widgets and several related classes [...] don't work in secondary threads.

You will have to notify your main (GUI) thread to update the UI. You can do so with signals & slots.

Adrian W
  • 4,563
  • 11
  • 38
  • 52