在for-loop Python 2.7中更新PyQt4进度条

2024-09-29 21:44:49 发布

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

我扩充了this example以允许我的用户知道当程序在For循环中处理一个RAM密集型迭代过程时,它处于进程的哪个部分。我发现下面的脚本在请求打印计数值并等待几秒钟时可以工作,但对于更密集的函数则不行。在

# from https://pythonspot.com/en/qt4-progressbar/

import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtCore import pyqtSlot,SIGNAL,SLOT
import time

class QProgBar(QProgressBar):

    value = 0

    @pyqtSlot()
    def increaseValue(progressBar):
        progressBar.setValue(progressBar.value)
        progressBar.value = progressBar.value+1

# Create an PyQT4 application object.
a = QApplication(sys.argv)       

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()

# Set window title  
w.setWindowTitle("PyQT4 Progressbar @ pythonspot.com ") 

# Create progressBar. 
bar = QProgBar(w)
bar.resize(320,50)    
bar.setValue(0)


bar.setAlignment(Qt.AlignCenter)
bar.move(0,50)

label = QLabel("test",w)
label.setStyleSheet("QLabel { font-size: 20px }")
label.setAlignment(Qt.AlignCenter)
label.move(0,10)

# create timer for progressBar
'''timer = QTimer()
bar.connect(timer,SIGNAL("timeout()"),bar,SLOT("increaseValue()"))
timer.start(400)'''

# Show window
w.show()

for i in range(0,100):
    print(i) 
    ### Do action
    bar.setValue(i)
    time.sleep(0.5)

sys.exit(a.exec_())

我能做些什么来让这个动作更激烈些吗?有没有人知道一个更好的进度条包,我可以很容易地插入for循环?在

一般来说,我对GUI开发还不熟悉,我只需要简单的UI

提前感谢您提供的任何帮助:)


Tags: fromimportcomforvaluesysbarlabel
1条回答
网友
1楼 · 发布于 2024-09-29 21:44:49

Qt不会更新UI,直到您将控制权交还给事件循环,也就是说,直到for循环结束。您可以通过如下方式调用processEvents,使事件循环更新UI:

for i in range(0,100):
    print(i) 
    ### Do action
    bar.setValue(i)
    a.processEvents()
    time.sleep(0.5)

相关问题 更多 >

    热门问题