gpt4 book ai didi

python - 启动时将参数传递给pyqt线程

转载 作者:太空宇宙 更新时间:2023-11-03 11:00:45 25 4
gpt4 key购买 nike

有什么方法可以在线程启动时(.start)将参数传递给 QThread 吗?

我在 stackoverflow 中找到了使用 pyqt 线程的示例,但我想知道如何传递参数,以防我希望工作线程处理我传递给它的 run() 函数的数据。

我引用的帖子:Busy indication with PyQt progress bar

代码:

class MyCustomWidget(QtGui.QWidget):

def __init__(self, parent=None):
super(MyCustomWidget, self).__init__(parent)
layout = QtGui.QVBoxLayout(self)

self.progressBar = QtGui.QProgressBar(self)
self.progressBar.setRange(0,100)
button = QtGui.QPushButton("Start", self)
layout.addWidget(self.progressBar)
layout.addWidget(button)

button.clicked.connect(self.onStart)

self.myLongTask = TaskThread()
self.myLongTask.notifyProgress.connect(self.onProgress)


def onStart(self):
self.myLongTask.start()

def onProgress(self, i):
self.progressBar.setValue(i)


class TaskThread(QtCore.QThread):
notifyProgress = QtCore.pyqtSignal(int)
def run(self):
for i in range(101):
self.notifyProgress.emit(i)
time.sleep(0.1)

我想在调用 .start 时传递一个变量,例如

self.myLongTask.start(myvar)
.
.
def run(self, myvar):

当然,pyqt 不允许这样做。

最佳答案

你不能将参数传递给 run 但你可以像这样将参数传递给它的构造函数:

class TaskThread(QtCore.QThread):
notifyProgress = QtCore.pyqtSignal(int)
def __init__(self, myvar, parent=None):
QThread.__init__(self, parent)
self.myvar = myvar
def run(self):
#use self.myvar in your run
for i in range(101):
self.notifyProgress.emit(i)
time.sleep(0.1)

MyCustomWidget 类中:

class MyCustomWidget(QtGui.QWidget):

def __init__(self, parent=None):
super(MyCustomWidget, self).__init__(parent)
layout = QtGui.QVBoxLayout(self)

self.progressBar = QtGui.QProgressBar(self)
self.progressBar.setRange(0,100)
button = QtGui.QPushButton("Start", self)
layout.addWidget(self.progressBar)
layout.addWidget(button)

button.clicked.connect(self.onStart)
##############################################################
#and pass your argumetn to it's constructor here
self.myLongTask = TaskThread(myvar=myargument)
##############################################################
self.myLongTask.notifyProgress.connect(self.onProgress)


def onStart(self):
self.myLongTask.start()

def onProgress(self, i):
self.progressBar.setValue(i)

关于python - 启动时将参数传递给pyqt线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33138706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com