0

我有以下两个文件:

import sys
import time
from PyQt4 import QtGui, QtCore

import btnModule

class WindowClass(QtGui.QWidget):

    def __init__(self):
        super(WindowClass, self).__init__()
        self.dataLoaded = None

#       Widgets

#       Buttons
        thread = WorkerForLoop(self.runLoop)
#        thread.start()
        self.playBtn    = btnModule.playpauselBtnClass \
                            ('Play', thread.start)            
#       Layout
        layout = QtGui.QHBoxLayout()
        layout.addWidget(self.playBtn)
        self.setLayout(layout)

#       Window Geometry
        self.setGeometry(100, 100, 100, 100)

    def waitToContinue(self):
        print self.playBtn.text()
        while (self.playBtn.text() != 'Pause'):
            pass

    def runLoop(self):
        for ii in range(100):
            self.waitToContinue()
            print 'num so far: ', ii
            time.sleep(0.5)

class WorkerForLoop(QtCore.QThread):
    def __init__(self, function, *args, **kwargs):
        super(WorkerForLoop, self).__init__()
        self.function = function
        self.args = args
        self.kwargs = kwargs

    def __del__(self):
        self.wait()

    def run(self):
        print 'let"s run it'
        self.function(*self.args, **self.kwargs)
        return



if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)

    wmain = WindowClass()
    wmain.show()

    sys.exit(app.exec_())

和第二个文件 btnModule.py:

from PyQt4 import QtGui, QtCore

class playpauselBtnClass(QtGui.QPushButton):

    btnSgn = QtCore.pyqtSignal()

    def __init__(self, btnName, onClickFunction):
        super(playpauselBtnClass, self).__init__(btnName)

        self.clicked.connect(self.btnPressed)
        self.btnSgn.connect(onClickFunction)

    def btnPressed(self):
        if self.text() == 'Play':
            self.setText('Pause')
            self.btnSgn.emit()
            print 'Changed to pause and emited signal'
        elif self.text() == 'Pause':
            self.setText('Continue')
            print 'Changed to Continue'
        elif self.text() == 'Continue':
            self.setText('Pause')
            print 'Changed to Pause'

如果在第一个文件中我删除了thread.start()它按预期工作的注释,它会启动线程然后挂起,直到我单击PlayUI。但是,我认为即使我没有在那里启动它也应该可以工作,因为信号btnSgn连接到onClickFunction在这种情况下采用 value thread.start

将此用作参考 http://joplaete.wordpress.com/2010/07/21/threading-with-pyqt4/

4

1 回答 1

2

我认为当您尝试在第二个文件(通过 self.btnSgn.emit())中调用 thread.start() 时它不起作用的原因是线程对象超出了您创建的init函数的范围它。所以你在一个已经删除的线程上调用 start() 。

当我尝试它时,只需更改线程 - > self.thread(即使线程对象成为 WindowClass 对象的成员)就可以正常工作,因为线程会一直保持活动状态直到程序结束。

于 2013-04-08T04:36:54.593 回答