Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

pyqt5 进度条多线程卡顿,求解?

点击按钮,启动进度条,也按网上方式用了多线程,但是还会卡顿,求解?

import sys
import time
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *


class test(QWidget):

    def __init__(self):
        super(test, self).__init__()

        self.setupUi()

    def setupUi(self):
        self.setFixedSize(500, 90)
        self.layout = QGridLayout()
        self.main_widget = QWidget(self)
        self.progressBar = QProgressBar()

        self.btn = QPushButton('start')

        self.layout.addWidget(self.progressBar,0,0,1,1)
        self.layout.addWidget(self.btn,1,0,1,1)
        self.setLayout(self.layout)

        # 创建并启用子线程
        self.thread_1 = Worker()
        self.thread_1.progressBarValue.connect(self.copy_file)

        self.btn.clicked.connect(self.ck)

    def ck(self):
        for i in range(101):
            time.sleep(0.1)
            self.thread_1.progressBarValue.emit(i)  # 发送进度条的值 信号

    def copy_file(self, i):
        self.progressBar.setValue(i)


class Worker(QThread):

    progressBarValue = pyqtSignal(int)  # 更新进度条

    def __init__(self):
        super(Worker, self).__init__()

    def run(self):
        self.progressBarValue.emit(1)  # 发送进度条的值 信号

if __name__ == '__main__':
    app = QApplication(sys.argv)
    testIns = test()
    testIns.show()
    sys.exit(app.exec_())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

time.sleep 会阻塞整个进程。
可以考虑使用threading.Event 的wait()方法


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...