Passing parameter to a pyqt thread when started

前端 未结 1 1520
时光说笑
时光说笑 2021-02-10 02:37

Is there any way we can pass a parameter to QThread when the thread is started (.start) ?

I found an example of using pyqt thread in stackoverflow, but I was wondering h

1条回答
  •  深忆病人
    2021-02-10 03:27

    You can not pass argument to run but you can pass argument to it's constructor like this:

    class TaskThread(QtCore.QThread):
        notifyProgress = QtCore.pyqtSignal(int)
        def __init__(self, myvar, parent=None):
            QThread.__init__(self, parent)
            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)
    

    and in the MyCustomWidget class:

    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)
    

    0 讨论(0)
提交回复
热议问题