我想将多个对象从 GUI (
MainWidget
) 发送到可以执行“长”任务的 Worker (QThread
),但不知道如何使用 QTheads
.
main.py代码:
import sys
from PySide6.QtWidgets import QWidget, QApplication
from ui_widget import Ui_Form
from class1 import Test1
from class2 import Test2
from class3 import Test3
from pathlib import Path
class MainWidget(QWidget, Ui_Form):
def __init__(self):
super().__init__()
self.setupUi()
files = Path()
self.t1 = Test1()
self.t1_temp = ""
self.t2 = Test2()
self.t2_temp = ""
self.t3 = Test3()
self.t3_temp = ""
self.pushButton.clicked.connect(self.check_and_run())
def check_and_run(self):
# Use checkbox to find what test to run
if (self.test1.isChecked()):
# Do some validation of user input...
# If everything ok, then make class object
self.t1 = Test1(self.test1_x.text(), self.test1_y.text())
if (self.test2.isChecked()):
# Do some validation of user input...
# If everything ok, then make class object
self.t2 = Test2(self.test2_x.text(), self.test2_y.text())
if (self.test3.isChecked()):
# Do some validation of user input...
# If everything ok, then make class object
self.t3 = Test3(self.test3_x.text(), self.test3_y.text())
self.run_test()
def run_test(self):
# Run the long tasks for each test if it applies
for file in self.files:
if (self.test1.isChecked()):
self.t1.run(self.t1_temp)
if (self.test2.isChecked()):
self.t2.run(self.t2_temp)
if (self.test2.isChecked()):
self.t3.run(self.t3_temp)
从上面的代码中,我想在工作线程中运行函数
run_test
。
我实现了下面的
QThread
类,但通过在 GUI 和 QThread
中初始化相同的变量不断重复自己,这是我理想情况下想要避免的。还有其他方法可以用WorkerThread
完成这种行为吗?
class WorkerThread(QThread):
def __init__(self, t1: Test1(), t2: Test2(), t3: Test3(), t1_temp: str,
t2_temp: str, t3_temp: str, files: Path, t1_flag: bool, t2_flag: bool, t3_flag: bool ) -> None:
super().__init__()
self.t1 = t1
self.t2 = t2
self.t3 = t3
self.t1_temp = t1_temp
self.t2_temp = t2_temp
self.t3_temp = t3_temp
self.t1_flag = t1_flag
self.t2_flag = t2_flag
self.t3_flag = t3_flag
self.files = files
def run(self):
for file in self.files:
if (self.t1_flag):
self.t1.run(self.t1_temp, file)
if (self.t2_flag):
self.t2.run(self.t2_temp)
if (self.t3_flag):
self.t3.run(self.t3_temp)