【发布时间】:2020-05-21 04:23:47
【问题描述】:
我正在尝试编写一些软件来处理从一些晶体学实验中收集的大量图像。数据处理包括以下步骤:
- 用户输入来确定要一起批处理的图像数量。
- 选择包含图像的目录,并计算图像总数。
- 嵌套的 for 循环用于将图像批处理在一起,并为使用批处理文件处理的每个批处理构造命令和参数。
下面的代码可以用来模拟使用QThread和QProcess描述的过程:
# This Python file uses the following encoding: utf-8
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import test
import time
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.ui=test.Ui_test()
self.ui.setupUi(self)
self.ui.pushButton_startThread.clicked.connect(self.startTestThread)
def startTestThread(self):
self.xValue = self.ui.lineEdit_x.text() #Represents number of batches
self.yValue = self.ui.lineEdit_y.text() #Represents number of images per batch
runTest = testThread(self.xValue, self.yValue) #Creates an instance of testThread
runTest.start() #Starts the instance of testThread
class testThread(QThread):
def __init__(self, xValue, yValue):
super().__init__()
self.xValue = xValue
self.yValue = yValue
def __del__(self):
self.wait()
def run(self):
for x in range(int(self.xValue)): #For loop to iterate througeach batch
print(str(x) + "\n")
for y in range(int(self.yValue)): #For loop to iterate through each image in each batch
print(str(y) + "\n")
print(y)
process = QProcess(self) #Creates an instance of Qprocess
process.startDetached("test.bat") #Runs test.bat
def stop(self):
self.terminate()
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setStyle("Fusion")
window = MainWindow()
window.show()
sys.exit(app.exec_())
test.bat 内容:
@ECHO OFF
ECHO this is a test
GUI 包含两个用于 xValue 和 yValue 的用户输入以及一个用于启动线程的按钮。例如,一项实验产生 150,000 张图像,需要分批处理 500 张图像。这将需要每批处理 300 张图像。您可以为 xValue 输入 500,为 yValue 输入 300。有两个问题:
- GUI 冻结,因此如果需要,我无法停止进程。我认为运行线程应该可以防止这种情况发生。
- 我收到以下错误:
QObject: Cannot create children for a parent that is in a different thread.
(Parent is testThread(0x1a413f3c690), parent's thread is QThread(0x1a4116cb7a0), current thread is testThread(0x1a413f3c690)
我相信这个错误是通过嵌套 for 循环生成多个 QProcesses 的结果,但我不完全确定。
是否有办法阻止 GUI 冻结并避免生成的错误?
【问题讨论】:
-
QProcess(self)可能会导致错误消息。run()在后台线程中调用,而self在主线程中引用testThread。 -
哦!谢谢!这就说得通了。修复了 QObject 错误!
标签: python pyqt5 python-multithreading qthread qprocess