我想与正在运行的子流程并行地更新小部件的状态

2024-06-25 23:22:23 发布

您现在位置:Python中文网/ 问答频道 /正文

代码如下:

def run_analyzer(self, analyzer, filename):
    is_set_to_zero = False

    p = subprocess.Popen([analyzer, filename], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

    line_iterator = iter(p.stdout.readline, b"")
    for line in line_iterator:
        is_set_to_zero = self.progBar(str(line), is_set_to_zero)  

def progBar(self, text, set_to_zero):

    if set_to_zero == False:
        self.core_progress_bar.setMinimum(0)
        self.core_progress_bar.setMaximum(0)
        return True

    if 'DONE' in text:
        self.core_progress_bar.setRange(0, 100)
        self.core_progress_bar.setValue(100)
        time.sleep(0.5)
        self.core_progress_bar.reset()

这背后的整个想法是让进度条在分析器工作时处于“忙碌”状态。一旦最后一行(包括单词DONE)被传递到progBar方法,它将闪烁绿色并返回到枯燥状态

它在调试模式下工作良好

然而,当它正常运行时,当分析器分析时,该条没有做任何事情。当它完成时,程序似乎终于记住了它应该对进度条做些什么,并且它呈绿色闪烁,就像我希望的那样

有没有办法让这些事情同时成为人们关注的焦点


Tags: tocoreselffalseisdeflinebar
1条回答
网友
1楼 · 发布于 2024-06-25 23:22:23

QT不会更新您的gui,因为它卡在方法的循环中,您必须将该循环移动到继承QtCore.QThread的类中,并创建/连接一个自定义信号到该线程,该线程将更新您的进度条

这里有一些例子:

class Progress(QtCore.QThread):
    def __init__(self):
        QtCore.QThread.__init__(self)
    def run():
        p = subprocess.Popen([analyzer, filename], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

        line_iterator = iter(p.stdout.readline, b"")
        for line in line_iterator:
            self.emit( QtCore.SIGNAL('__updateProgressBar(int)', yourPercentNumber))


class YourMainClass:
    #blabla...
    self.progressThread = Progress()
    self.connect(self.progressThread, QtCore.SIGNAL("__updateProgressBar(int)"), self.progBar)

    @QtCore.Slot(int)
    def progBar(percent):
        #blabla

相关问题 更多 >