How can I pass arguments to QThread Worker class?

2019-08-12 08:15发布

This question already has an answer here:

I have a working example of code that creates a QThread that must be called from my on class (MyClass). I have tried passing additional arguments through the Worker init, but I can't get it to work.

How can I pass 1 or more arguments to my Worker thread with this working code?

from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtCore import * 

class Worker(QThread):
    processdone = QtCore.pyqtSignal("QString") # Define custom signal.
    def __init__(self, parent=None):
        QThread.__init__(self, parent)
    def run(self):
        print("do worker thread processing here")
        self.emit( SIGNAL('processdone'), "DONE")
        return       

class MyClass(QObject):

    def __init__(self):            
        super(MyClass, self).__init__()   

        thread1 = Worker(self) 
        self.connect( thread1, SIGNAL("processdone"), self.thread1done)  
        thread1.start()  

    def thread1done(self, text):
        print(text)                      # Print the text from the signal.
        sys.exit()

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)  
    a = MyClass()
    sys.exit(app.exec_())

I found this stackoverflow question which is very similar, however I can not get the accepted answer to work with my above code: Passing an argument when starting new QThread() in PyQt

1条回答
The star\"
2楼-- · 2019-08-12 09:08

No, I think is not duplicated question, it have more to do ...

Anyway, Your question your want to pass more argument, In python your can pass many argument call 'yourMethod(*args, **kw)'; example;

class Worker(QThread):
    .
    .
    def __init__(self, parent, *args, **kw):
        QThread.__init__(self, parent)
        self.yourInit(*args, **kw)
    .
    .
    def yourInit (self, x, y, z):
        print x, y, z
    .
    .

class MyClass(QObject):
        .
        .
    def __init__(self):            
        super(MyClass, self).__init__()   
        .
        .
        x = 1000
        y = 'STRING'
        z = [0, 1, 2, 3, 4]
        thread1 = Worker(self, x, y, z)
        .
        .

Regards,

查看更多
登录 后发表回答