KarimS
KarimS

Reputation: 3902

PyQt QThread cause main thread to close

Hello i have a problem with creating Thread using the QThread class. here is my code :

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import QThread

class ScriptRunner(QThread):

    def run(self):
        print('test')


if __name__ == '__main__':

    app = QApplication(sys.argv)
    gui = QWidget()
    gui.setFixedSize(400, 400)
    gui.setVisible(True)

    ScriptRunner().start() # this line cause the error

    sys.exit(app.exec_())

when i lunch this code without the ScriptRunner().start() line, the gui is working without any problem, but when i do add the line, the gui show up and is hidden very quickly and program is shutdown

I receive this message in the console :

/usr/bin/python3.6 /home/karim/upwork/python-qt-rasp/tests/test.py
QThread: Destroyed while thread is still running

Process finished with exit code 134 (interrupted by signal 6: SIGABRT)

Upvotes: 0

Views: 597

Answers (2)

KarimS
KarimS

Reputation: 3902

The problem was that you must save a reference to the thread that you lunch, in my real world example, i was not saving a reference to the thread in my object, so its was garbage collected by python i think.

self.runner = Runner()

Upvotes: 1

Szabolcs
Szabolcs

Reputation: 4106

Please change the line:

ScriptRunner().start() # this line cause the error

to:

sr = ScriptRunner()
sr.start()

Tested for PyQt4 though, but works.

EDIT:

Another workaround that worked for me:

Instantiating ScriptRunner as ScriptRunner(gui).start() also works.

Upvotes: 1

Related Questions