简体   繁体   English

PyQt QThread导致主线程关闭

[英]PyQt QThread cause main thread to close

Hello i have a problem with creating Thread using the QThread class. 您好,我在使用QThread类创建Thread时遇到问题。 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 当我在没有ScriptRunner().start()行的情况下使用此代码时,gui可以正常工作,但是当我添加该行时,gui就会显示并很快被隐藏,并且程序关闭

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. 经过PyQt4的测试,但是可以工作。

EDIT: 编辑:

Another workaround that worked for me: 对我有用的另一个解决方法:

Instantiating ScriptRunner as ScriptRunner(gui).start() also works. ScriptRunner(gui).start()实例ScriptRunner ScriptRunner(gui).start()也可以。

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

self.runner = Runner()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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