小能豆

PyQt5 QThread.self.setTerminationEnabled(False) 似乎不起作用

javascript

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_()

我可能是错的,但 根据https://doc.qt.io/qtforpython-6/PySide6/QtCore/QThread.html#PySide6.QtCore.PySide6.QtCore.QThread.setTerminationEnabledlooper.setTerminationEnabled(False)预期或self.setTerminationEnabled(False)阻止 QThread 。terminate()

但对我来说这是行不通的。有什么提示吗??

我在用Qt: v 5.15.2 PyQt: v 5.15.7


阅读 92

收藏
2023-05-29

共1个答案

小能豆

setTerminationEnabled是一个静态方法。它不会启用或禁用调用它的线程的终止,事实上,您根本不应该在 QThread 实例上调用它。

setTerminationEnabled启用或禁用调用 的线程setTerminationEnabled的终止。您需要从线程中调用它looper。不,将它放入__init__不会那样做 -__init__不会由新线程执行。那个线程甚至还没有开始。你需要调用它run

def run(self):
    QTCore.QThread.setTerminationEnabled(False)
    ...
2023-05-29