我正在尝试制作一个复制大文件的进度条。但是,当前对话框窗口变黑直到进程完成。我现在明白了,我可能需要学习如何使用treads并将数据传回GUI。但我还是不明白为什么窗口不能完全渲染。我可以理解窗口是否因为moveFilesWithProgress
函数正在运行而没有响应。但在该函数中,我正在更新进度条值。我甚至尝试添加QtGui.QGuiApplication.processEvents()
,希望它能在继续迭代之前更新gui。在
如果没有多线程进程可以解决这个问题,我将非常感谢任何帮助,但是如果不可能的话,我将非常感谢一个关于如何使用Qthread的简单示例。我发现了一个相关的问题,但要理解这个例子还有很多事情要做。here is the link
#!/usr/bin/env python
import os
import sys
import shutil
from PyQt5.QtWidgets import (QApplication, QDialog, QLineEdit, QMainWindow,
QPushButton, QProgressBar)
import PyQt5.QtGui as QtGui
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.button = QPushButton("Copy", self)
self.button.clicked.connect(self.archiveEntry)
self.show()
def archiveEntry(self):
self.p = ProgressBar()
self.p.show()
Dir = "/media/zachlab/Windows/LinuxStorage/old/embryos"
outDir = "/media/zachlab/Windows/LinuxStorage/old/out"
run = self.p.moveFilesWithProgress(Dir, outDir)
# if run:
# self.p.close
class ProgressBar(QDialog):
def __init__(self):
super().__init__()
self.pbar = QProgressBar(self)
def timerEvent(self, e):
if self.step >= 100:
self.timer.stop()
self.btn.setText('Finished')
return
self.pbar.setValue(self.step)
def update(self, value):
self.pbar.setValue(value)
QtGui.QGuiApplication.processEvents()
def calculateAndUpdate(self, done, total):
progress = int(round((done / float(total)) * 100))
self.update(progress)
def countFiles(self, directory):
files = []
if os.path.isdir(directory):
for path, dirs, filenames in os.walk(directory):
files.extend(filenames)
return len(files)
def makedirs(self, dest):
if not os.path.exists(dest):
os.makedirs(dest)
def moveFilesWithProgress(self, src, dest):
numFiles = self.countFiles(src)
if os.path.exists(dest):
return 0
if numFiles > 0:
self.makedirs(dest)
numCopied = 0
for path, dirs, filenames in os.walk(src):
for directory in dirs:
destDir = path.replace(src, dest)
self.makedirs(os.path.join(destDir, directory))
for sfile in filenames:
srcFile = os.path.join(path, sfile)
destFile = os.path.join(path.replace(src, dest), sfile)
shutil.copy(srcFile, destFile)
numCopied += 1
self.calculateAndUpdate(numCopied, numFiles)
self.show()
return 1
else:
return 0
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = MainWindow()
sys.exit(app.exec_())
繁重的任务不应该在主线程上运行,应该使用线程。在本例中,我替换了您的逻辑,因此有一个类负责复制文件,通过进度、错误等迹象通知。该类的对象将位于另一个线程中,通过信号通知GUI,在这种情况下,我将使用QProgressDialog来显示进度。在
相关问题 更多 >
编程相关推荐