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 libsfrom PyQt4.QtGui import *
import sys # import sys and url handlers import urllib2class Form(QDialog): # creat form class
def __init__(self, parent=None): super(Form, self).__init__(parent) # instantiate classdate = self.getdata() # set variables from methods below rates = sorted(self.rates.keys()) dateLabel = QLabel(date)self.fromComboBox = QComboBox() # set form items self.fromComboBox.addItems(rates) self.fromSpinBox = QDoubleSpinBox() self.fromSpinBox.setRange(0.01, 1000000.00) self.fromSpinBox.setValue(1.00) self.toComboBox = QComboBox() self.toComboBox.addItems(rates) 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) self.setLayout(grid)# set form and widget signals self.connect(self.fromComboBox, SIGNAL("currentIndexChanged(int)"), self.updateUI) self.connect(self.toComboBox, SIGNAL("currentIndexChanged(int)"), self.updateUI) self.connect(self.fromSpinBox, SIGNAL("valueChanged(double)"), self.updateUI)self.setWindowTitle(“Currency”)
def updateUI(self): # set method called by signalsto = 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.fromSpinBox.value() self.toLabel.setText("%0.2f" % amount)def getdata(self): # method to get the data and populate the formself.rates = {} try:date = "Unknown" fh = urllib2.urlopen("http://www.bankofcanada.ca" "/en/markets/csv/exchange_eng.csv") # datafor line in fh:if not line or line.startswith(("#", "Closing")):continue # discard lines we don't wantfields = line.split(",") # split csv dataif line.startswith("Date"): date = fields[-1] # get dateelse:try:value = float(fields[-1]) # convert rate to float self.rates[unicode(fields[0])] = value # create key:value (currency:exch rate) pair in dictexcept ValueError:pass return "Exchange rate date: " + dateexcept Exception, e:return "Failed to download:\n%s" % e# show forms app = QApplication(sys.argv) form = Form() form.show() app.exec_()
Leave a Reply