如何将参数传递给QThread工作类?

1 投票
1 回答
4712 浏览
提问于 2025-04-18 17:58

我有一段可以正常工作的代码,这段代码创建了一个QThread(线程),需要在我的类(MyClass)中调用。我尝试通过Worker的init方法传递额外的参数,但一直没能成功。

我该如何在这段正常工作的代码中,给我的Worker线程传递一个或多个参数呢?

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_())

我找到一个在StackOverflow上的问题,跟我的情况很相似,不过我无法让被接受的答案在我的代码上运行:在PyQt中启动新QThread时传递参数

1 个回答

4

不,我觉得这个问题不是重复的,它涉及的内容更多……

不过,你的问题是想传递更多的参数。在Python中,你可以通过一种叫做 'yourMethod(*args, **kw)' 的方式来传递多个参数;举个例子:

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)
        .
        .

祝好,

撰写回答