如何在不阻止GUI的情况下将QThread中生成的多个列表返回到主线程?
我正在寻找在线程中使用xlwings进行耗时的工作,然后在线程完成后我希望能够在主线程中使用这些列表。有没有简单的方法可以做到这一点?
我可以考虑做一些事情,例如将线程中的值添加到全局列表并在主线程中访问它们。
from PyQt5 import QtCore, QtWidgets
import sys
class Ui_Calculations(object):
def setupUi(self, Calculations):
Calculations.setObjectName("Calculations")
Calculations.resize(850, 363)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Calculations.sizePolicy().hasHeightForWidth())
Calculations.setSizePolicy(sizePolicy)
Calculations.setMinimumSize(QtCore.QSize(850, 350))
Calculations.setMaximumSize(QtCore.QSize(860, 363))
self.centralwidget = QtWidgets.QWidget(Calculations)
self.centralwidget.setObjectName("centralwidget")
Calculations.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(Calculations)
self.menubar.setGeometry(QtCore.QRect(0, 0, 850, 21))
self.menubar.setObjectName("menubar")
self.menuScreenshot = QtWidgets.QMenu(self.menubar)
self.menuScreenshot.setObjectName("menuScreenshot")
Calculations.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(Calculations)
self.statusbar.setObjectName("statusbar")
Calculations.setStatusBar(self.statusbar)
self.actionScreenshot = QtWidgets.QAction(Calculations)
self.actionScreenshot.setObjectName("actionScreenshot")
self.menuScreenshot.addAction(self.actionScreenshot)
self.menubar.addAction(self.menuScreenshot.menuAction())
self.retranslateUi(Calculations)
QtCore.QMetaObject.connectSlotsByName(Calculations)
def retranslateUi(self, Calculations):
_translate = QtCore.QCoreApplication.translate
Calculations.setWindowTitle(_translate("Calculations", "Calculations"))
self.menuScreenshot.setTitle(_translate("Calculations", "File"))
self.actionScreenshot.setText(_translate("Calculations", "Screenshot"))
class mainClass(QtWidgets.QMainWindow, Ui_Calculations):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.thread = exampleThread()
self.thread.finished.connect(self.run_return)
self.thread.start()
def run_return(self):
#do something with return values
print(exampleList[-1])
print(example1List[-1])
class exampleThread(QtCore.QThread):
"""Example thread"""
finished = QtCore.pyqtSignal()
def __init__(self,parent = None):
super().__init__(parent)
def run(self):
exampleList = [5,4,3]
example1List = [5,4,3]
self.finished.emit()
#return exampleList,example1List
def main():
app = QtWidgets.QApplication(sys.argv)
exampleWindow = mainClass()
app.processEvents()
exampleWindow.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
答案 0 :(得分:1)
您可以pass known Python types as parameters when you emit a signal。
在您的示例中,更改“信号”的声明以包含要传递的数据类型,这两种数据类型均为list
:
finished = QtCore.pyqtSignal(list, list)
然后让相应的“ slot”接受两个参数:
def run_return(self, list1, list2):
print(list1[-1])
print(list2[-1])