本篇文章是一篇关于模块文本的帖子
接上一篇GUI编程的日记,在现我们来写一个常正点程序。先让我们看一下程序的子样。
看似常正多了。我们有了一个框框,一个X。而且不须要命令行入输了!
根据上一篇日记所述,我们须要载入模块。
先载入QT4所用的模块以及算计所用的math模块。
from __future__ import division #准确除法 import sys from math import * from PyQt4.QtCore import * from PyQt4.QtGui import *
根据截图,这个应用程序用了两个widgets ,一个是QTextBrowser这是一个只读的文本或者HTML查看器, 另一个是QLineEdit 是一个单行的可写的文本查看器。
根据QT的则规,全部的字符都为Uni编码。
def __init__(self, parent=None): super(Form, self).__init__(parent) self.browser = QTextBrowser() self.lineedit = QLineEdit("Type an expression and press Enter") self.lineedit.selectAll() layout = QVBoxLayout() layout.addWidget(self.browser) layout.addWidget(self.lineedit) self.setLayout(layout) self.lineedit.setFocus() self.connect(self.lineedit, SIGNAL("returnPressed()"), self.updateUi) self.setWindowTitle("Calculate coding by Kaysin")
这样就完成了初始画面的义定。
QVBoxLayout() 就是一个可以放置widget的面页。
而上面的addWidget法方,就是将所建创的widget添加进新的面页。
上面有触发信号,按下回车。
载入函数 upadteUi
def updateUi(self): try: text = unicode(self.lineedit.text()) self.browser.append("%s = <b>%s</b>" % (text, eval(text))) except: self.browser.append( "<font color=red>%s is invalid!</font>" % text)
这个很好解理,就是断判入输是不是正当,出现异常则出输不正当。
我们看下源程序。
from __future__ import division import sys from math import * from PyQt4.QtCore import * from PyQt4.QtGui import * class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) self.browser = QTextBrowser() self.lineedit = QLineEdit("Type an expression and press Enter") self.lineedit.selectAll() layout = QVBoxLayout() layout.addWidget(self.browser) layout.addWidget(self.lineedit) self.setLayout(layout) self.lineedit.setFocus() self.connect(self.lineedit, SIGNAL("returnPressed()"), self.updateUi) self.setWindowTitle("Calculate coding by Kaysin") def updateUi(self): try: text = unicode(self.lineedit.text()) self.browser.append("%s = <b>%s</b>" % (text, eval(text))) except: self.browser.append( "<font color=red>%s is invalid!</font>" % text) app = QApplication(sys.argv) form = Form() form.show() app.exec_()
文章结束给大家分享下程序员的一些笑话语录: 现在社会太数字化了,所以最好是有一个集很多功能于一身的设备!