#!/usr/bin/env python
#encoding:utf-8
# Copyright (c) 2007-8 Qtrac Ltd. All rights reserved.
# This program or module is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 2 of the License, or
# version 3 of the License, or (at your option) any later version. It is
# provided for educational purposes and is distributed in the hope that
# it will be useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
# the GNU General Public License for more details.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):
#没有parent的部件就成为一个顶级窗口
super(Form, self).__init__(parent)
#QTextBrowser多行文本部件,可以显示纯文本和HTML
self.browser = QTextBrowser()
#QLineEdit单行文本部件,只能显示纯文本
self.lineedit = QLineEdit("Type an expression and press Enter")
#selectAll全选
self.lineedit.selectAll()
#QVBoxLayout垂直排列部件的布局类
layout = QVBoxLayout()
#往布局对象中添加部件
layout.addWidget(self.browser)
layout.addWidget(self.lineedit)
#设置实例的布局管理器
self.setLayout(layout)
#聚焦
self.lineedit.setFocus()
#将信号连接到插槽,returnPressed信号是Return或Enter键被按下,这个在class reference里有说明。
self.connect(self.lineedit, SIGNAL("returnPressed()"),
self.updateUi)
#设置窗口标题
self.setWindowTitle("Calculate")
def updateUi(self):
try:
#转换为unicode字符串
text = unicode(self.lineedit.text())
#eval计算表达式
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_()