python - 如何在 python 中终止 qthread

标签 python pyside qthread terminate

我有一个 GUI 应用程序,它使用 qwebview 通过长循环进行 Web 自动化处理,所以我使用 QThread 来执行此操作,但我无法终止线程,我的代码如下

class Main(QMainWindow):
    def btStart(self):
        self.mythread = BrowserThread()
        self.connect(self.mythread, SIGNAL('loop()'), self.campaign_loop, Qt.AutoConnection)
        self.mythread.start()

    def btStop(self):
        self.mythread.terminate()

    def campaign_loop(self):
        loop goes here

class BrowserThread(QThread):
    def __init__(self):
        QThread.__init__(self)

    def run(self):
        self.emit(SIGNAL('loop()'))

此代码在启动线程时工作正常,但无法停止循环,浏览器仍在运行,即使我对其调用关闭事件并且它从 GUI 中消失也是如此

最佳答案

编辑:它也可以在 linux 上运行,我在 raspberry pi 4 上试过它并且运行良好

重点是在“run”方法中创建主循环,因为“terminate”函数是在“run”中停止循环而不是线程本身 这是一个工作示例,但不幸的是它只适用于 Windows

import sys
import time
from PySide.QtGui import *
from PySide.QtCore import *

class frmMain(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.btStart = QPushButton('Start')
        self.btStop = QPushButton('Stop')
        self.counter = QSpinBox()
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.btStart)
        self.layout.addWidget(self.btStop)
        self.layout.addWidget(self.counter)
        self.setLayout(self.layout)
        self.btStart.clicked.connect(self.start_thread)
        self.btStop.clicked.connect(self.stop_thread)

    def stop_thread(self):
        self.th.stop()

    def loopfunction(self, x):
        self.counter.setValue(x)

    def start_thread(self):
        self.th = thread(2)
        #self.connect(self.th, SIGNAL('loop()'), lambda x=2: self.loopfunction(x), Qt.AutoConnection)
        self.th.loop.connect(self.loopfunction)
        self.th.setTerminationEnabled(True)
        self.th.start()

class thread(QThread):
    loop = Signal(object)

    def __init__(self, x):
        QThread.__init__(self)
        self.x = x

    def run(self):
        for i in range(100):
            self.x = i
            self.loop.emit(self.x)
            time.sleep(0.5)

    def stop(self):
        self.terminate()


app = QApplication(sys.argv)
win = frmMain()

win.show()
sys.exit(app.exec_())

关于python - 如何在 python 中终止 qthread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26833093/

相关文章:

python - 使用 python 客户端从 yaml 创建 Kubernetes CronJob

python - 无法在 for 循环中重置计数器

python - PySide/PyQt 覆盖小部件

c++ - 我的 QThread 已完成,但我无法收到信号

python - PyQt5 从另一个模块发出信号

Python - 如何仅将两个列表中的某些数字相乘

python - 将 xml 转换为字典时处理错误

python - 如何使用 Qt/PySide 实现逆霍夫变换?

python - 如何在PySide的浏览器示例中添加工具栏?

linux - 如何在 Linux 中获取 QThread 的 PID?