Final code for the week

Moving on through the tasks in the Rapid GUI book, I have worked through the following example. Basic Dialog based GUI creation seems straightforward, so next week I will concentrate on Main based apps and getting some scientific functionality into the code behind the GUI.

from PyQt4.QtCore import * # import QtCore and GUI libs

from PyQt4.QtGui import *

import sys # import sys and url handlers
import urllib2

class Form(QDialog): # creat form class

def __init__(self, parent=None):
super(Form, self).__init__(parent) # instantiate class
date = self.getdata() # set variables from methods below
rates = sorted(self.rates.keys())
dateLabel = QLabel(date)
self.fromComboBox = QComboBox() # set form items
self.fromSpinBox = QDoubleSpinBox()
self.fromSpinBox.setRange(0.01, 1000000.00)
self.toComboBox = QComboBox()
self.toLabel = QLabel("1.00")
grid = QGridLayout() # set form layout
grid.addWidget(dateLabel, 0, 0)
grid.addWidget(self.fromComboBox, 1, 0)
grid.addWidget(self.fromSpinBox, 1, 1)
grid.addWidget(self.toComboBox, 2, 0)
grid.addWidget(self.toLabel, 2, 1)
# set form and widget signals
SIGNAL("currentIndexChanged(int)"), self.updateUI)
SIGNAL("currentIndexChanged(int)"), self.updateUI)
SIGNAL("valueChanged(double)"), self.updateUI)


def updateUI(self): # set method called by signals
to = unicode(self.toComboBox.currentText()) # get currency
from_ = unicode(self.fromComboBox.currentText())
# calculate amount based on values in dictionary {rates}
amount = (self.rates[from_] / self.rates[to])*\
self.toLabel.setText("%0.2f" % amount)
def getdata(self): # method to get the data and populate the form
self.rates = {}
date = "Unknown"
fh = urllib2.urlopen(""
"/en/markets/csv/exchange_eng.csv") # data
for line in fh:
if not line or line.startswith(("#", "Closing")):
continue # discard lines we don't want
fields = line.split(",") # split csv data
if line.startswith("Date"):
date = fields[-1] # get date
value = float(fields[-1]) # convert rate to float
self.rates[unicode(fields[0])] = value
# create key:value (currency:exch rate) pair in dict
except ValueError:
return "Exchange rate date: " + date
except Exception, e:
return "Failed to download:\n%s" % e
# show forms
app = QApplication(sys.argv)
form = Form()
Tagged ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: