如何将参数传递给 QThread Worker 类? [英] How can I pass arguments to QThread Worker class?

查看:56
本文介绍了如何将参数传递给 QThread Worker 类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码的工作示例,它创建一个必须从我的班级 (MyClass) 中调用的 QThread.我曾尝试通过 Worker init 传递额外的参数,但我无法让它工作.

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.

如何使用此工作代码将 1 个或多个参数传递给我的工作线程?

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

我发现这个 stackoverflow 问题非常相似,但是我无法得到可接受的答案来处理我上面的代码:在 PyQt 中启动 new QThread() 时传递参数

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

推荐答案

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

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

无论如何,你的问题是你想传递更多的参数,在 python 中你可以传递许多参数调用 'yourMethod(*args, **kw)';例子;

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

<小时>

问候,

这篇关于如何将参数传递给 QThread Worker 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆