本文介绍了如何在pyqt中同时运行两个不同的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一种情况,我需要一个接一个地启动两个线程.我尝试了以下代码片段,在这里我可以启动Thread12,但不能启动Thread2.我怎样才能同时开始...?如何启动两个线程中的另一个...?
I have a situation where i need to start two threads one after the other. I tried the following code snippet, here i could able to start the Thread12 but not able to start Thread2. How can i start both....?How to start 2 threads one ofter the other...?
代码段
class Thread1(QtCore.QThread):
Thread1Signal = QtCore.pyqtSignal(str)
def __init__(self):
super(Thread1, self).__init__()
def run(self):
print 'Thread1 started'
While True:
#some statments
if Condition:
Thread1Signal.emit('Yes')
else:
Thread1Signal.emit('No')
class Thread2(QtCore.QThread):
Thread2Signal = QtCore.pyqtSignal(str)
def __init__(self):
super(Thread2, self).__init__()
def run(self):
print 'Thread2 started'
While True:
#some statments
if Condition:
Thread2Signal.emit('Yes')
else:
Thread2Signal.emit('No')
class MainClass(QtCore.QObject):
MainSignal1 = QtCore.pyqtSignal(str)
MainSignal2 = QtCore.pyqtSignal(str)
def __init__(self):
super(MainClass, self).__init__()
Threadinstance1 = Thread1()
Threadinstance1.Thread1Signal.connect(MainSignal1)
Threadinstance2 = Thread2()
Threadinstance2.Thread2Signal.connect(MainSignal2)
def start(self):
Threadinstance1.start()
Threadinstance2.start() #Thread2 never starts.
def signal1called(s):
print s
def signal2called(s):
print s
if __name__=='__main__':
app = AtGui.QApplication(sys.argv)
temp = MainClass()
temp.MainSignal1.connect(signal1called)
temp.MainSignal2.connect(signal2called)
temp.start()
sys.exit(app.exec()_)
推荐答案
您将使用QRunnable
和QThreadPool
,如下所示:
You will be using QRunnable
and QThreadPool
, something like this:
import sys
from PyQt4.QtGui import QApplication
from PyQt4.QtCore import QThreadPool, QObject, QRunnable, pyqtSignal
class WorkerSignals(QObject):
result = pyqtSignal(int)
class Worker(QRunnable):
def __init__(self, task):
super(Worker, self).__init__()
self.task = task
self.signals = WorkerSignals()
def run(self):
print 'Sending', self.task
self.signals.result.emit(self.task)
class Tasks(QObject):
def __init__(self):
super(Tasks, self).__init__()
self.pool = QThreadPool()
self.pool.setMaxThreadCount(1)
def process_result(self, task):
print 'Receiving', task
def start(self):
for task in range(10):
worker = Worker(task)
worker.signals.result.connect(self.process_result)
self.pool.start(worker)
self.pool.waitForDone()
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
main = Tasks()
main.start()
sys.exit(app.exec_())
这篇关于如何在pyqt中同时运行两个不同的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!