我有一个有3个不同窗口的应用程序。其中一个包括:
开始按钮
停止按钮
LCDNumber显示
当我按下开始按钮时,计时器启动并且LCDNumber显示屏上显示已用时间。然而,当我按下停止时,整个GUI卡住,没有任何作用,没有按钮等。我知道这是因为此代码中使用的while循环。但是我不知道如何使用while循环有效地停止工作线程。请给我一些提示,也许解决我的问题。
TimerWindow实例在 main 中创建。正如您所见,TimerWindow构造函数创建了一个myThread类实例。 myThread类实例创建timerThread类实例。我希望你看这段代码时很明显。如果你需要完整的代码,请在评论中告诉我,我会发布:) 我的代码基于this example
按钮连接到以下方法:
QtCore.QObject.connect(self.STARTbutton, QtCore.SIGNAL(_fromUtf8("clicked()")), TimerWindow.on_button_clicked)
QtCore.QObject.connect(self.STOPbutton, QtCore.SIGNAL(_fromUtf8("clicked()")), TimerWindow.on_myThread_finished)
以下是课程
class TimerWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self,parent)
self.ui_timer = Ui_TimerWindow() #create instance of Ui_TimerWindow
self.ui_timer.setupUi(self) #call setupUi which will create all the GUI elements
self.myThread = myThread(self)
self.myThread.timeElapsed.connect(self.on_myThread_timeElapsed)
self.myThread.finished.connect(self.on_myThread_finished)
@QtCore.pyqtSlot()
def on_button_clicked(self):
self.myThread.start()
@QtCore.pyqtSlot(int)
def on_myThread_timeElapsed(self, seconds):
self.ui_timer.lcdNumber.display(seconds)
@QtCore.pyqtSlot()
def on_myThread_finished(self):
self.myThread.terminate()
print "Done"
东西
class myThread(QtCore.QThread):
"""this is the main thread class called when we want to create a timer"""
timeElapsed = QtCore.pyqtSignal(float)
def __init__(self, parent=None):
super(myThread, self).__init__(parent)
self.timerThread = timerThread(self) #create an instance of timerThread class
self.timerThread.timeElapsed.connect(self.timeElapsed.emit)
def run(self):
self.timerThread.start(time.time())
iterations = 10000000000
while iterations:
print "Running {0}".format(self.__class__.__name__)
iterations -= 1
time.sleep(100)
class timerThread(QtCore.QThread):
"""instance of this class i created when myThread class object is created and myThread's class constructor is used"""
timeElapsed = QtCore.pyqtSignal(float)
def __init__(self, parent=None):
super(timerThread, self).__init__(parent)
self.timeStart = None
def start(self, timeStart):
self.timeStart = timeStart
return super(timerThread, self).start()
def run(self):
while self.parent().isRunning():
self.timeElapsed.emit(time.time() - self.timeStart)
time.sleep(1)