views:

551

answers:

1

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?

+2  A: 

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:

http://doc.trolltech.com/4.4/threads.html

Chris Cameron