英文:
PyQt5 QThread.self.setTerminationEnabled(False) seems not to work
问题
以下是您提供的代码的翻译部分:
from PyQt5 import QtCore, QtGui, QtWidgets
class Looper(QtCore.QThread):
"""QThread,逐个将自然数打印到标准输出。"""
def __init__(self, *args, **kwargs):
super(Looper, self).__init__(*args, **kwargs)
# self.setTerminationEnabled(True)
self.setTerminationEnabled(False)
def run(self):
i = 0
while True:
self.msleep(100)
print(i)
i += 1
# 初始化并启动循环线程。
looper = Looper()
looper.setTerminationEnabled(False)
looper.start()
# 主线程休眠5秒。
QtCore.QThread.sleep(3)
# 终止循环线程。
looper.terminate()
app = QtWidgets.QApplication([])
app.exec_()
希望这对您有所帮助。
英文:
borrowing from https://stackoverflow.com/questions/27961098/pyside-qthread-terminate-causing-fatal-python-error I tried this example:
from PyQt5 import QtCore, QtGui, QtWidgets
class Looper(QtCore.QThread):
"""QThread that prints natural numbers, one by one to stdout."""
def __init__(self, *args, **kwargs):
super(Looper, self).__init__(*args, **kwargs)
# self.setTerminationEnabled(True)
self.setTerminationEnabled(False)
def run(self):
i = 0
while True:
self.msleep(100)
print(i)
i += 1
# Initialize and start a looper.
looper = Looper()
looper.setTerminationEnabled(False)
looper.start()
# Sleep main thread for 5 seconds.
QtCore.QThread.sleep(3)
# Terminate looper.
looper.terminate()
app = QtWidgets.QApplication([])
app.exec_()
I could be wrong, but expected looper.setTerminationEnabled(False)
or self.setTerminationEnabled(False)
to prevent the QThread from terminate()
according to https://doc.qt.io/qtforpython-6/PySide6/QtCore/QThread.html#PySide6.QtCore.PySide6.QtCore.QThread.setTerminationEnabled.
But to me it doesn't work. Any hint ??
I am using Qt: v 5.15.2 PyQt: v 5.15.7
答案1
得分: 2
setTerminationEnabled
是一个静态方法。它不会启用或禁用调用它的线程的终止,并且事实上,你根本不应该在 QThread 实例上调用它。
setTerminationEnabled
启用或禁用调用 setTerminationEnabled
的线程的终止。你需要从 looper
线程中调用它。而且,把它放在 __init__
中是不行的 - __init__
不会被新线程执行。那个线程甚至还没有开始。你需要在 run
中调用它:
def run(self):
QTCore.QThread.setTerminationEnabled(False)
...
英文:
setTerminationEnabled
is a static method. It doesn't enable or disable termination of the thread it's called on, and in fact, you're not supposed to call it on a QThread instance at all.
setTerminationEnabled
enables or disables termination of the thread that calls setTerminationEnabled
. You need to call it from the looper
thread. And no, putting it in __init__
doesn't do that - __init__
is not executed by the new thread. That thread hasn't even started yet. You need to call it in run
:
def run(self):
QTCore.QThread.setTerminationEnabled(False)
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论