PyQt测试(QThread线程和自定义信号):用QProgressDialog显示拷贝进度

粗糙的测试代码……

from PyQt5.Qt import *
import sys, shutil, os, time


class CopyFile(QThread):
    # 该线程负责拷贝文件,并且自定义了一个路径错误信号:当路径不正确是不会开始拷贝,并发送信号
    pathError = pyqtSignal()
    def setFile(self,src, dst):
        # 线程开启之前首先要在外部调用该方法,设置好源和目标路径
        self.src = src
        self.dst = dst
    def run(self):
        if os.path.exists(self.src):
            shutil.copy2(self.src, self.dst)
        else:
            self.pathError.emit()

class CopyProgress(QThread):
    # 该线程负责实时检查拷贝的剩余量,并且返回已经拷贝的百分比整型值。
    checked = pyqtSignal(int)
    def setFile(self, src, dst):
        # 线程开启之前首先要在外部调用该方法,设置好源和目标路径
        self.src = src
        self.dst = dst
        self.value = 0

    def run(self):
        while 1:
            time.sleep(1)
            if os.path.getsize(self.src)>os.path.getsize(self.dst):
                self.value = int(os.path.getsize(self.dst)/os.path.getsize(self.src)*100)
            else:
                self.value = 100
            if self.value == 100:
                self.checked.emit(100)
                break

            self.checked.emit(self.value)

class Mwindow(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,200)
        self.src = "../movie4.mkv"
        self.dst = "E:\\movie4.mkv"
        self.initui()
    def initui(self):
        self.pg = QProgressDialog(self)
        self.pg.setMinimumDuration(1)

        button = QPushButton(self)
        button.setText("测试-开始拷贝")
        button.clicked.connect(lambda:self.copy_file())


    def copy_file(self):
        self.copy_thread = CopyFile()
        self.copy_thread.setFile(self.src,self.dst)
        self.copy_thread.pathError.connect(lambda:print("路径错误"))
        self.copy_thread.start()
        self.show_copy()

    def show_copy(self):
        self.show_progress = CopyProgress()
        self.show_progress.start()
        self.show_progress.setFile(self.src, self.dst)
        self.show_progress.checked.connect(lambda v:self.pg.setValue(v))




app = QApplication(sys.argv)

w = Mwindow()
w.show()

sys.exit(app.exec_())

你可能感兴趣的:(笔记,pyqt,python)