简体   繁体   中英

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)

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.

问题在于您必须保存对您午饭使用的线程的引用,在我的实际示例中,我没有在对象中保存对该线程的引用,因此我认为它是由python垃圾收集的。

self.runner = Runner()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM