我试图制作一个在我正在运行的长时间过程中运行的脉动进度条,完成后它将完全变成绿色。我已经在这里阅读过一些以前的文章,但是我无法弄清楚为此所需的线程。

import time

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(770, 726)
        self.progressBar = QtGui.QProgressBar(Form)
        self.progressBar.setGeometry(QtCore.QRect(150, 590, 118, 23))
        self.progressBar.setProperty("value", 24)
        self.progressBar.setTextVisible(False)
        self.progressBar.setObjectName(_fromUtf8("progressBar"))

        self.pushButton = QtGui.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(25, 50, 170, 40))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.pushButton.clicked.connect(self.onStart)

        self.myLongTask = TaskThread()
        self.myLongTask.taskFinished.connect(self.onFinished)



        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def onStart(self):
        self.progressBar.setRange(0,0)
        self.myLongTask.start()

    def onFinished(self):
        # Stop the pulsation
        self.progressBar.setRange(0,1)

    def retranslateUi(self, Form):
        Form.setWindowTitle(_translate("Form", "Form", None))
        self.pushButton.setText(_translate("Form", "Run", None))

    def test(self):
        for i in xrange(500000):
            print i

class TaskThread(QtCore.QThread):
    taskFinished = QtCore.pyqtSignal()
    def run(self):
        time.sleep(3)
        self.taskFinished.emit()

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Form = QtGui.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())


现在,酒吧刚刚跳动。它永远不会达到测试定义。我知道这是因为我没有正确地调用它,但是我不确定如何同时运行脉动和def测试。

最佳答案

好,要在进度条旋转时使test()方法起作用,您可以执行以下操作:

class TaskThread(QtCore.QThread):
    taskFinished = QtCore.pyqtSignal()
    def run(self):
        # instead of sleeping do the long running loop
        for i in xrange(500000):
            print i
        self.taskFinished.emit()


并从test()中删除​​Ui_form方法。整个想法是,您需要在另一个线程中而不是在处理主窗口的主线程中执行长时间运行的任务。

10-08 00:35