在 PyQt 中启动 new QThread() 时传递参数
我有一个用 Python 编写的多线程应用程序,其中一个线程“照顾”GUI,另一个线程是工作线程。但是,工作线程有两个主要函数(或者说两个主要作业),我需要告诉运行函数到底要执行哪个作业。
所以我的想法是在工作线程中创建一个运行函数,该函数将采用一个参数(除了“self”)。该参数要么是“create”,要么是上传。言归正传,这里是我编写的代码到目前为止:
GUI.py
class GUI(QMainWindow):
def __init__(self, parent=None):
super, etc
self.worker = worker.Worker()
def create(self):
self.worker.start()
def upload(self):
self.worker.start()
Worker.py
class Worker(QThread):
def __init__(self, parent=None):
super, etc
def run(self):
self.create_data() # OR self.upload_data(), depends
所以问题是,我如何告诉worker.start()我希望它执行哪个功能?我意识到可以直接使用worker.run()方法,但有人告诉我“使用 PyQT 进行快速 GUI 开发” 从不直接调用worker.run(),并且总是使用worker.start()。
I have a multi-threaded application written in Python in which one thread "takes care" of the GUI, and the other is the worker thread. However, the worker thread has two main functions (or so to say two main jobs), and I need to tell the run function which job exactly to do.
So what I had in mind was to create a run function in the worker thread which will take one parameter (save for "self). The parameter will either be "create" or upload. Without further ado, here's the somewhat-code that I have so far:
GUI.py
class GUI(QMainWindow):
def __init__(self, parent=None):
super, etc
self.worker = worker.Worker()
def create(self):
self.worker.start()
def upload(self):
self.worker.start()
Worker.py
class Worker(QThread):
def __init__(self, parent=None):
super, etc
def run(self):
self.create_data() # OR self.upload_data(), depends
So the question is, how can I tell worker.start() which function I want it to perform? I realize one could directly use worker.run() method, but I was told by the "Rapid GUI development with PyQT" never to call worker.run() directly, and always to use worker.start().
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
QThread
的start
方法不接受参数。但是,您继承了QThread
,因此您可以随意自定义它。因此,要实现您想要的功能,只需将参数传递到 Worker 的构造函数中即可。这是您的代码示例,稍作修改以显示其实际效果:
The
start
method ofQThread
doesn't accept arguments. However, you've inheritedQThread
so you're free to customize it at will. So, to implement what you want, just pass arguments into the constructor ofWorker
.Here's your code sample slightly modified to show this in action:
Eli Bendersky 的答案是正确的,但论证的顺序似乎是错误的。
如果您像这样调用 Worker 类:
对我有用的参数顺序:
Eli Bendersky 的答案中显示的顺序为我产生了此错误消息:
不知道为什么,但我确信有人可以帮助解释。
Eli Bendersky's answer is correct, however the order of arguments appears wrong.
If you call the Worker class like this:
The argument order that worked for me:
The order shown in Eli Bendersky's answer produced this error message for me:
Not sure why, but I'm sure someone can help explain.