为什么在 macOS 上使用 QThread 时 PyQt 应用程序会崩溃或挂起?
Why does PyQt application crash or hang when using QThread on macOS?
在 PyQt5 中调用线程 class 时,应用程序崩溃并出现错误:QThread: Destroyed while thread is still 运行 if I don't添加
def __del__(self):
self.wait()
将上述语句添加到线程class后,应用程序运行但停止,直到线程完成执行(基本上使线程无用)。我是 运行 macOS Catalina 10.15.6,Intel i9,Python 3.7.4。有什么办法可以解决这个问题?这是代码(ui window 中只有一个按钮):
from PyQt5.QtWidgets import QMainWindow
from PyQt5 import QtWidgets, uic
from PyQt5.QtCore import QThread, pyqtSignal
import sys, time
class Main(QMainWindow):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
uic.loadUi('main.ui', self)
self.btn1.clicked.connect(self.run_worker)
def run_worker(self):
worker = Worker_thread()
worker.start()
class Worker_thread(QThread):
def __init__(self):
QThread.__init__(self)
def __del__(self):
self.wait()
def run(self):
time.sleep(10)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
win = Main()
win.show()
sys.exit(app.exec_())
问题很简单:“worker”变量是一个局部变量,当它的作用域结束时,它就被消除了,在这种情况下,作用域是“run_worker”函数。当去掉“运行”方法时,不是在管理QThread的副线程中执行,而是在阻塞GUI的主线程中执行。
解决方案是扩展其范围,例如通过使 class 属性:
def run_worker(self):
self.worker = Worker_thread()
self.worker.start()
注意:问题与OS无关。
在 PyQt5 中调用线程 class 时,应用程序崩溃并出现错误:QThread: Destroyed while thread is still 运行 if I don't添加
def __del__(self):
self.wait()
将上述语句添加到线程class后,应用程序运行但停止,直到线程完成执行(基本上使线程无用)。我是 运行 macOS Catalina 10.15.6,Intel i9,Python 3.7.4。有什么办法可以解决这个问题?这是代码(ui window 中只有一个按钮):
from PyQt5.QtWidgets import QMainWindow
from PyQt5 import QtWidgets, uic
from PyQt5.QtCore import QThread, pyqtSignal
import sys, time
class Main(QMainWindow):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
uic.loadUi('main.ui', self)
self.btn1.clicked.connect(self.run_worker)
def run_worker(self):
worker = Worker_thread()
worker.start()
class Worker_thread(QThread):
def __init__(self):
QThread.__init__(self)
def __del__(self):
self.wait()
def run(self):
time.sleep(10)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
win = Main()
win.show()
sys.exit(app.exec_())
问题很简单:“worker”变量是一个局部变量,当它的作用域结束时,它就被消除了,在这种情况下,作用域是“run_worker”函数。当去掉“运行”方法时,不是在管理QThread的副线程中执行,而是在阻塞GUI的主线程中执行。
解决方案是扩展其范围,例如通过使 class 属性:
def run_worker(self):
self.worker = Worker_thread()
self.worker.start()
注意:问题与OS无关。