如何在python中终止qthread

Moh*_*sof 1 python terminate pyside qthread

我有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()'))
Run Code Online (Sandbox Code Playgroud)

这个代码在启动线程时工作正常但是无法停止循环并且浏览器仍在运行,即使我向它调用close事件并且它从GUI中消失

Moh*_*sof 6

关键是在"运行"方法中使主循环,因为"终止"函数在"运行"中停止循环而不是它自己的线程在这里是一个工作示例,但遗憾的是它仅适用于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_())
Run Code Online (Sandbox Code Playgroud)

  • 不鼓励使用self.terminate。参见/sf/ask/1957276891/ (2认同)