How do I make this progress bar close when it is d

2019-05-25 13:22发布

I commonly write Python scipts to do conversion tasks for me and whenever I write one that takes a while I use this little progress bar to check on it

import sys
import time
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
barra = QtGui.QProgressBar()
barra.show()
barra.setMinimum(0)
barra.setMaximum(10)
for a in range(10):
    time.sleep(1)
    barra.setValue(a)
app.exec_()

I have 2 questions:

How do I make it close itself when it reaches 100% (It stays open and if you close the python shell before clicking the X button you crash it.)

also, When it loses and regains focus, it stops painting correctly. the process will continue to completion but the progress bar space is all white. How do I handle this?

1条回答
爷、活的狠高调
2楼-- · 2019-05-25 13:40

Well, because you set your Maximum to 10, your progress bar shouldn't reach 100% because

for a in range(10):
  time.sleep(1)
  barra.setValue(a)

will only iterate up to 9.

Progress bars don't close automatically. You will have to call

barra.hide()

after your loop.

As for the paint problem, it's likely because whatever script you ran this script from is in the same thread as the progress bar. So when you switch away and back the paint events are delayed by the actual processing of the parent script. You can either set a timer to periodically call .update() or .repaint() on 'barra' (update() is recommended over repaint()) OR you would want your main processing code to run in a QThread, which is also available in the PyQt code, but that will require some reading on your part :)

The doc is for Qt, but it applies to PyQt as well:

https://doc.qt.io/qt-4.8/threads.html

查看更多
登录 后发表回答