我有一种情况,我想使用单个 QThread 在不同时间运行两个(或更多)单独的方法。例如,我希望 QThreadplay()
有时运行,当我玩完时,我想断开 QThread 与此方法的连接,以便我可以将它连接到其他地方。本质上,我希望 QThread 充当我想与主进程并行运行的任何东西的容器。
我遇到了启动 QThread 然后立即断开它会导致运行时出现奇怪行为的问题。在我发现“竞态条件”是什么意思(或者真正了解多线程)之前,我偷偷怀疑线程在断开连接之前还没有完全启动。start()
为了克服这个问题,我在and调用之间添加了 5 毫秒的睡眠,disconnect()
它就像一个魅力。它就像一个魅力,但它不是正确的方式。
如何在不调用 QThread 的情况下使用一个 QThread 实现此功能sleep()
?
有问题的代码片段:
def play(self):
self.stateLabel.setText("Status: Playback initated ...")
self.myThread.started.connect(self.mouseRecorder.play)
self.myThread.start()
time.sleep(.005) #This is the line I'd like to eliminate
self.myThread.started.disconnect()
完整脚本:
class MouseRecord(QtCore.QObject):
finished = QtCore.pyqtSignal()
def __init__(self):
super(MouseRecord, self).__init__()
self.isRecording = False
self.cursorPath = []
@QtCore.pyqtSlot()
def record(self):
self.isRecording = True
self.cursorPath = []
while(self.isRecording):
self.cursorPath.append(win32api.GetCursorPos())
time.sleep(.02)
self.finished.emit()
def stop(self):
self.isRecording = False
@QtCore.pyqtSlot()
def play(self):
for pos in self.cursorPath:
win32api.SetCursorPos(pos)
time.sleep(.02)
print "Playback complete!"
self.finished.emit()
class CursorCapture(QtGui.QWidget):
def __init__(self):
super(CursorCapture, self).__init__()
self.mouseRecorder = MouseRecord()
self.myThread = QtCore.QThread()
self.mouseRecorder.moveToThread(self.myThread)
self.mouseRecorder.finished.connect(self.myThread.quit)
self.initUI()
def initUI(self):
self.recordBtn = QtGui.QPushButton("Record")
self.stopBtn = QtGui.QPushButton("Stop")
self.playBtn = QtGui.QPushButton("Play")
self.recordBtn.clicked.connect(self.record)
self.stopBtn.clicked.connect(self.stop)
self.playBtn.clicked.connect(self.play)
self.stateLabel = QtGui.QLabel("Status: Stopped.")
#Bunch of other GUI initialization ...
def record(self):
self.stateLabel.setText("Status: Recording ...")
self.myThread.started.connect(self.mouseRecorder.record)
self.myThread.start()
time.sleep(.005)
self.myThread.started.disconnect()
def play(self):
self.stateLabel.setText("Status: Playback initated ...")
self.myThread.started.connect(self.mouseRecorder.play)
self.myThread.start()
time.sleep(.005)
self.myThread.started.disconnect()