【问题标题】:How can I pass arguments to QThread Worker class? [duplicate]如何将参数传递给 QThread Worker 类? [复制]
【发布时间】:2014-10-14 08:14:57
【问题描述】:

我有一个代码的工作示例,它创建了一个必须从我的 on 类 (MyClass) 调用的 QThread。我已经尝试通过 Worker init 传递其他参数,但我无法让它工作。

如何使用此工作代码将 1 个或多个参数传递给我的 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 问题非常相似,但是我无法使用上面的代码得到公认的答案:Passing an argument when starting new QThread() in PyQt

【问题讨论】:

  • 为什么你不能得到公认的答案来工作?传入参数:thread1 = Worker(self, some_argument)...这怎么行?

标签: python mysql pyqt pyqt4 qthread


【解决方案1】:

不,我认为不是重复的问题,它还有更多工作要做......

无论如何,您的问题是您想传递更多参数,在 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)
        .
        .

问候,

【讨论】:

    猜你喜欢
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    • 2012-03-12
    • 2013-11-18
    • 2021-04-16
    相关资源
    最近更新 更多