我试图了解线程是如何工作的,但我遇到了这个问题。这是我的程序的解释: 我在 pyqt 中制作了一个简单的 GUI,使用 QObject 作为工作类。当我按下按钮时,GUI从列表中读取一个随机值并将其传递给线程,打印 接下来的五个数字。当线程完成工作时,它将数据传递给 GUI。现在我希望 GUI 自动重新启动一个具有新起始值的新线程。我可以通过再次按开始来重新启动线程,但我需要在没有人工交互的情况下启动它。在那儿 有什么方法吗?
提前致谢
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import time
import sys
import numpy as np
class SomeObject(QObject):
finished = pyqtSignal(object)
valore = pyqtSignal(object)
vector = pyqtSignal(object)
def __init():
super(SomeObject, self).__init__()
def longRunning(self):
vec = []
end = self.count + 5
while self.count < end:
time.sleep(1)
vec.append(self.count)
self.valore.emit(self.count)
self.count += 1
self.finished.emit(vec)
#self.vector.emit()
def setCount(self, num):
self.count = num
class GUI(QDialog):
def __init__(self, parent = None):
super(GUI, self).__init__(parent)
#declare QThread object
self.objThread = QThread()
#declare SomeObject type, and move it to thread
self.obj = SomeObject()
self.obj.moveToThread(self.objThread)
#connect finished signal to nextVector method
self.obj.finished.connect(self.nextVector)
#connect valore to self.prova method
self.obj.valore.connect(self.prova)
#self.obj.vector.connect(self.nextVector)
#Connect thread.start to the method long running
self.objThread.started.connect(self.obj.longRunning)
botton = QPushButton("start")
self.connect(botton, SIGNAL("clicked()"), self.showcount)
box = QHBoxLayout()
box.addWidget(botton)
self.setLayout(box)
#a list of random number
a = np.random.randint(10, size = 5)
self.iter = iter(a)
def showcount(self):
"""
When botton clicked, read the next value from iter, pass it to
setCount and when start the thread
"""
try:
a = self.iter.next()
print a
self.obj.setCount(a)
self.objThread.start()
except StopIteration:
print "finito"
#self.obj.setCount(a)
#self.objThread.start()
#print self.objThread.currentThreadId()
def prova(self, value):
"""
Connected to signal valore, print the value
"""
print value
def nextVector(self, vec):
"""
Print the whole vector
"""
print vec
self.objThread.quit()
try:
a = self.iter.next()
print a
self.obj.setCount(a)
self.objThread.start()
except StopIteration:
print "finito"
app = QApplication(sys.argv)
form = GUI()
form.show()
app.exec_()
最佳答案
您已经设置好了。当你的线程完成时,它会发出调用 nextVector 方法的完成信号,因此只需在 nextVector 末尾调用 start 方法即可。
def nextVector(self, vec):
...
self.showcount()
# end nextVector
您可能还想更改 QPushButton 的新信号连接
button.clicked.connect(self.showcount)
关于python - PyQt Qthread自动重启,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24754219/