启动时将参数传递给pyqt线程

时间:2015-10-15 02:15:17

标签: python pyqt pyqt4 qthread

有什么方法可以在线程启动时将参数传递给QThread(.start)?

我在stackoverflow中找到了一个使用pyqt线程的例子,但是我想知道如何传递参数,以防我希望工作线程处理我传递给它的run()函数的数据。

我引用的帖子:Busy indication with PyQt progress bar

代码:

class MyCustomWidget(QtGui.QWidget):

    def __init__(self, parent=None):
        super(MyCustomWidget, self).__init__(parent)
        layout = QtGui.QVBoxLayout(self)       

        self.progressBar = QtGui.QProgressBar(self)
        self.progressBar.setRange(0,100)
        button = QtGui.QPushButton("Start", self)
        layout.addWidget(self.progressBar)
        layout.addWidget(button)

        button.clicked.connect(self.onStart)

        self.myLongTask = TaskThread()
        self.myLongTask.notifyProgress.connect(self.onProgress)


    def onStart(self):
        self.myLongTask.start()

    def onProgress(self, i):
        self.progressBar.setValue(i)


class TaskThread(QtCore.QThread):
    notifyProgress = QtCore.pyqtSignal(int)
    def run(self):
        for i in range(101):
            self.notifyProgress.emit(i)
            time.sleep(0.1)

我想在调用.start时传递变量,例如

self.myLongTask.start(myvar)
.
.
def run(self, myvar):

但当然,pyqt不允许这样做。

1 个答案:

答案 0 :(得分:2)

您无法将参数传递给run,但您可以将参数传递给它的构造函数如下:

class TaskThread(QtCore.QThread):
    def __init__(self, myvar, parent=None):
        QThread.__init__(self, parent)
        self.notifyProgress = QtCore.pyqtSignal(int)
        self.myvar = myvar
    def run(self):
        #use self.myvar in your run 
        for i in range(101):
            self.notifyProgress.emit(i)
            time.sleep(0.1)

并在MyCustomWidget班级中:

class MyCustomWidget(QtGui.QWidget):

    def __init__(self, parent=None):
        super(MyCustomWidget, self).__init__(parent)
        layout = QtGui.QVBoxLayout(self)       

        self.progressBar = QtGui.QProgressBar(self)
        self.progressBar.setRange(0,100)
        button = QtGui.QPushButton("Start", self)
        layout.addWidget(self.progressBar)
        layout.addWidget(button)

        button.clicked.connect(self.onStart)
        ##############################################################
        #and pass your argumetn to it's constructor here
        self.myLongTask = TaskThread(myvar=myargument)
        ##############################################################
        self.myLongTask.notifyProgress.connect(self.onProgress)


    def onStart(self):
        self.myLongTask.start()

    def onProgress(self, i):
        self.progressBar.setValue(i)