I have a QThread which runs, but will often need to be killed, then recreated. The problem is I'm getting an untraceable TypeError that pops up and I have no idea what's causing it. I presume I'm not exiting the thread properly or destroying it properly or some such s开发者_Go百科illyness, but I just haven't a clue what's causing it. Here's some code snippets:
Here's the code together:
class getHistory(QThread):
def __init__(self):
QThread.__init__(self)
self.killSwitch = 0
def kill(self):
self.killSwitch = 1
self.wait()
def run(self):
try:
for x in theloop:
hist = QTreeWidgetItem()
hist.data = dataStuff
self.emit(SIGNAL('histItem'), hist)
if self.killSwitch == 1: break
except: pass
self.emit(SIGNAL('string'), 'done')
return
class Main(QtGui.QMainWindow):
def __init__(self, args):
QtGui.QMainWindow.__init__(self)
self.runTheThread()
def doFunction(self, string):
if not string == 'done':
doThreadStuff
else:
doFinishedThreadStuff
def runTheThread(self):
self.theThread= getHistory()
self.connect(self.theThread, QtCore.SIGNAL("string"), self.doFunction)
self.theThread.start()
Then to try to kill it before looping, I kill theThread with self.theThread.kill()
All the proper things as far as killing the thread appear to be happening, except, if the thread is killed and restarted fast enough, I'll get an untraceable error:
TypeError: doFunction() takes exactly 2 arguments (1 given)
Also, on a slightly related note, is it wise/smart/right to check if a thread is done by emitting a string such as "Done" that is picked up by doFunction, or is there a better way to do it?
As doFunction is part of a Qt application, the two parameters are self, string. The code works until it is spammed, really, and only then does it present the error.
Thanks in advance.
Well, as error states clearly: You are sending self.doFunction just one parameter (the string "AllDone" in this case):
self.emit(SIGNAL('string'), 'AllDone')
but, I'll take a wild guess (since you didn't share the definition of doFunction) that it is defined as taking two parameters. So, anytime you emit the "string" signal you are bound to get that error.
As for the signal, if it's sole purpose is to shout that the thread is completed its run, QThread already has a "finished()" signal that is emitted when run is completed. Just use that.
On a side note: If you are using PyQt4.5+ consider using new-style signal and slots. They are more pythonic.
精彩评论