Run Multiple Qthreads Concurrently In Python
In the attached code when you click start it creates a QSpinBox and starts counting to 20 in QThread, but if I click start again while it is counting, the first QSpinBox stops and
Solution 1:
I made a few key changes:
- kept a list of the separate threads as you were overwriting the same thread object,
- fixed the recursive error when stopping a thread; used
terminate
instead, - thread keeps track of it's own index so it knows which spin box to update.
It's not really clear what you want to happen when you press stop, or press start after stopping, but this code should more or less work for you:
import sys
import time
from PySide.QtGui import *
from PySide.QtCore import *
classfrmMain(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)
self.boxes = []
self.threads = []
defstop_thread(self):
for th in self.threads:
th.terminate()
defloopfunction(self, n, index):
self.boxes[index].setValue(n)
defstart_thread(self):
index = len(self.threads)
th = thread(index)
th.loop.connect(self.loopfunction)
th.setTerminationEnabled(True)
th.start()
self.threads.append(th)
self.boxes.append(QSpinBox())
self.layout.addWidget(self.boxes[index])
classthread(QThread):
loop = Signal(int, int)
def__init__(self, index):
QThread.__init__(self)
self.index = index
defrun(self):
for n inrange(20):
self.loop.emit(n, self.index)
time.sleep(0.5)
app = QApplication(sys.argv)
win = frmMain()
win.show()
sys.exit(app.exec_())
Post a Comment for "Run Multiple Qthreads Concurrently In Python"