您好我在使用QThread类创建Thread时遇到问题。 这是我的代码:
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_())
当我在没有ScriptRunner().start()
行的情况下午餐时,gui工作没有任何问题,但是当我添加行时,gui显示并且很快被隐藏并且程序关闭
我在控制台中收到此消息:
/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)
答案 0 :(得分:1)
请更改行:
ScriptRunner().start() # this line cause the error
为:
sr = ScriptRunner()
sr.start()
虽然经过PyQt4测试,但仍有效。
编辑:
另一种对我有用的解决方法:
将ScriptRunner
实例化为ScriptRunner(gui).start()
也可以。
答案 1 :(得分:1)
问题是你必须保存对你午餐的线程的引用,在我的真实世界的例子中,我没有在我的对象中保存对线程的引用,所以我认为它是由python收集的垃圾。
self.runner = Runner()