在PyQt中启动新的QThread()时传递参数 [英] Passing an argument when starting new QThread() in PyQt
问题描述
我有一个用Python编写的多线程应用程序,其中一个线程负责" GUI,另一个线程是工作线程.但是,工作线程有两个主要功能(或者说两个主要作业),我需要告诉run函数确切地执行哪个作业.
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.
所以我想到的是在工作线程中创建一个运行函数,该函数将有一个参数(保存为"self").该参数将为"create"或upload.到目前为止的代码:
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
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 ().
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().
推荐答案
QThread
的start
方法不接受参数.但是,您已经继承了QThread
,因此可以随意自定义它.因此,要实现所需的功能,只需将参数传递到Worker
的构造函数中即可.
The start
method of QThread
doesn't accept arguments. However, you've inherited QThread
so you're free to customize it at will. So, to implement what you want, just pass arguments into the constructor of Worker
.
以下是对您的代码示例进行了一些修改,以显示其实际效果:
Here's your code sample slightly modified to show this in action:
class Worker(QThread):
def __init__(self, do_create_data=True, parent=None):
super(QThread, self).__init__()
self.do_create_data = create_data
def run(self):
if self.create_data:
self.create_data()
else:
self.upload_data(), depends
这篇关于在PyQt中启动新的QThread()时传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!