3

问题

我有一个 PyQt GUI,用户在其中按下一个按钮来启动一个后台线程(workerThread,它是 的子类QThread)。我想要一个计时器显示(以 a 的形式QLabel)来显示自开始以来已经过去了多少时间workerThread,我希望这个计时器在workerThread退出后立即停止。

可能的解决方案

我考虑过创建另一个timerThread独立QTimer线程QLabel(这timerThread将在收到来自 的终止信号后立即退出workerThread

但是,我必须同时开始timerThreadWorkerThread而且我不知道该怎么做。

问题

有没有更简单的方法来做到这一点?甚至是QTimer正确的方法开始吗?

4

1 回答 1

6

这是执行此操作的一种方法。在此示例中,在调用其方法时将其作为子进程myThread启动。它的信号连接到s信号。将每秒检查一次并在以下情况下发出信号:timerThreadruntimeElapsedtimerThreadtimeElapsedtimerThreadwhileparent isRunningtimeElapsedTrue

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import time

from PyQt4 import QtCore, QtGui

class timerThread(QtCore.QThread):
    timeElapsed = QtCore.pyqtSignal(int)

    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)


class myThread(QtCore.QThread):
    timeElapsed = QtCore.pyqtSignal(int)
    def __init__(self, parent=None):
        super(myThread, self).__init__(parent)

        self.timerThread = timerThread(self)
        self.timerThread.timeElapsed.connect(self.timeElapsed.emit)

    def run(self):
        self.timerThread.start(time.time())

        iterations = 3
        while iterations:
            print "Running {0}".format(self.__class__.__name__)
            iterations -= 1
            time.sleep(2)        


class myWindow(QtGui.QWidget):    
    def __init__(self):
        super(myWindow, self).__init__() 

        self.button = QtGui.QPushButton(self)
        self.button.setText("Start Threading!")
        self.button.clicked.connect(self.on_button_clicked)

        self.label = QtGui.QLabel(self)

        self.layout = QtGui.QVBoxLayout(self)
        self.layout.addWidget(self.button)
        self.layout.addWidget(self.label)

        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.label.setText("Time Elapsed: {0}".format(seconds))

    @QtCore.pyqtSlot()
    def on_myThread_finished(self):
        print "Done"

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('myWindow')

    main = myWindow()
    main.show()

    sys.exit(app.exec_())
于 2013-01-16T22:36:51.290 回答