编写一个计算复利的对话框应用程序。做好的效果如下图
先上代码,然后讲解。
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class interest(QDialog):
def __init__(self,parent=None):
super(interest,self).__init__(parent)
PrincipalLabel = QLabel("&Princinpal:")
self.PrincipalDoublespinBox = QDoubleSpinBox()
self.PrincipalDoublespinBox.setRange(0,10000) #set range
self.PrincipalDoublespinBox.setValue(0) #set value
self.PrincipalDoublespinBox.setPrefix("$") #set Prefix
PrincipalLabel.setBuddy(self.PrincipalDoublespinBox)# the first paragraph
RateLabel = QLabel("&Rate:")
self.RateDoublespinBox = QDoubleSpinBox()
self.RateDoublespinBox.setRange(0,100)
self.RateDoublespinBox.setValue(0)
self.RateDoublespinBox.setSuffix('%') #set suffix
RateLabel.setBuddy(self.RateDoublespinBox) #the second paragraph
self.list={"1years":1,"2years":2,"3years":3,"4years":4,"5years":5} #create a dict
item = sorted(self.list.keys())
YearsLabel = QLabel("&Years:")
self.YearsComboBox = QComboBox()
self.YearsComboBox.addItems(item) #get the keys of list,set items of ComboBox
YearsLabel.setBuddy(self.YearsComboBox) #the third paragraph
AmountTextLabel = QLabel("Amount")
self.AmountNumLabel = QLabel("0") #the fourth paragraph
layout = QGridLayout()
layout.addWidget(PrincipalLabel,0,0)
layout.addWidget(self.PrincipalDoublespinBox,0,1)
layout.addWidget(RateLabel,1,0)
layout.addWidget(self.RateDoublespinBox,1,1)
layout.addWidget(YearsLabel,2,0)
layout.addWidget(self.YearsComboBox,2,1)
layout.addWidget(AmountTextLabel,3,0)
layout.addWidget(self.AmountNumLabel,3,1)
self.setLayout(layout) #set the layout the fifth paragraph
self.connect(self.RateDoublespinBox,
SIGNAL("valueChanged(double)"),self.updateUi) #value of DoublespinBox
self.connect(self.PrincipalDoublespinBox,
SIGNAL("valueChanged(double)"),self.updateUi) #value of DoublespinBox,the type must be correct,or else can't connect
self.connect(self.YearsComboBox,
SIGNAL("currentIndexChanged(int)"),self.updateUi) #the index value,is numbers:0,1,2,3,4,and also take care of the signal
self.setWindowTitle("compound interest") #the sixth paragraph
def updateUi(self):
principal = self.PrincipalDoublespinBox.value() #get the value with the function of "value()"
rate = self.RateDoublespinBox.value()
years = unicode(self.YearsComboBox.currentText()) #get the Text of the "text ComboBox" with the function of "currentText()"
amount = principal*((1+(rate/100.0))**self.list[years])
self.AmountNumLabel.setText(unicode(amount)) #setText_function,Qstring argument #the seventh paragraph
app = QApplication(sys.argv)
computer = interest()
computer.show()
app.exec_() #the eighth paragraph