[英]how to terminate qthread in python
我有一個 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()'))
此代碼在啟動線程中運行良好,但無法停止循環並且瀏覽器仍在運行,即使我向它調用 close 事件並且它從 GUI 中消失
編輯:它也適用於 linux,我在 raspberry pi 4 上試過了,它工作正常
關鍵是在“運行”方法中創建主循環,因為“終止”函數正在停止“運行”中的循環而不是線程本身,這里是一個工作示例, 但不幸的是它只適用於 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_())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.