python – 关于GUI计时器的建议,以显示后台线程的已用时间?

问题

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

可能解决方案

我已经考虑过创建另一个独立线程(timerThread),该线程使用QTimer向槽发送信号,以便每隔1秒经过一段时间来更新主GUI线程中的QLabel.一旦从workerThread收到终止信号,此timerThread将立即退出.

但是,我必须在WorkerThread的同时启动timerThread,我不知道如何做到这一点.

有更简单的方法吗? QTimer甚至是正确的方法吗?

解决方法:

这是一种做到这一点的方法.在这个例子中,当调用run方法时,myThread将timerThread作为子进程启动.它的timeElapsed信号连接到timerThreads timeElapsed信号.当父正在运行时,timerThread将检查每秒,如果为True,则发出timeElapsed信号:

#!/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_())
上一篇:QT开发遇到的问题(1)——程序循环执行的问题


下一篇:windows平台使用 pthreads库