--- author: '' category: '' date: 2010/09/14 12:56 description: '' link: '' priority: '' slug: BB917 tags: kde, open source, programming, pyqt, python, qt title: Very pythonic progress dialogs. type: text updated: 2010/09/14 12:56 url_type: '' --- Sometimes, you see a piece of code and it just feels *right*. Here's an example I found when doing my "Import Antigravity" session for PyDay Buenos Aires: the ``progressbar`` module. Here's an example that will teach you enough to use ``progressbar`` effectively: .. code-block:: python progress = ProgressBar() for i in progress(range(80)): time.sleep(0.01) Yes, that's it, you will get a nice ASCII progress bar that goes across the terminal, supports resizing and moves as you iterate from 0 to 79. The ``progressbar`` module even lets you do fancier things like ETA or fie transfer speeds, all just as nicely. Isn't that code just *right*? You want a progress bar for that loop? Wrap it and you have one! And of course since I am a PyQt programmer, how could I make PyQt have something as *right* as that? Here'show the output looks like: .. raw:: html progress You can do this with every toolkit, and you probably should!. It has one extra feature: you can interrupt the iteration. Here's the (short) code: .. code-block:: python # -*- coding: utf-8 -*- import sys, time from PyQt4 import QtCore, QtGui def progress(data, *args): it=iter(data) widget = QtGui.QProgressDialog(*args+(0,it.__length_hint__())) c=0 for v in it: QtCore.QCoreApplication.instance().processEvents() if widget.wasCanceled(): raise StopIteration c+=1 widget.setValue(c) yield(v) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) # Do something slow for x in progress(xrange(50),"Show Progress", "Stop the madness!"): time.sleep(.2) Have fun!