2008-08-07

PyQt Sample -- Calculater

這是個來自Qtrac的程式,出自Rapid GUI PRogramming with Python and Qt一書.


#!/usr/bin/env python
# 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):
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")


def updateUi(self):
try:
text = unicode(self.lineedit.text())
self.browser.append("%s = %s" % (text, eval(text)))
except:
self.browser.append(
"%s is invalid!" % text)


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

from __future__ import division
import sys
from math import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *

一開始為了傳遞參數跟使用所有數學函數,所以匯入sys跟math這兩個函式庫. 其次是把QtCore跟QtGui這兩個PyQT函式庫也匯入.這樣就可以繼續…
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")

一般的GUI的Form是透過class來呈現,回應使用者的互動部份才是透過method, 而主程式通常都很短! 這裡的class 用了super()是用來設定這視窗,因為它是最上一層,所以parent=None. 而QTextBrowser則是一個只能顯示而不能修改的瀏覽區域, 透過QLineEdit則是可以提供一行的編輯區域。QVBoxLayout則是把視窗設定為垂直的排列, 先是browser區,後是lineedit區. 而當有人按下return鍵, 將會更新Ui畫面, 而updateUi則是一個使用者定義的function.
def updateUi(self):
try:
text = unicode(self.lineedit.text())
self.browser.append("%s = %s" % (text, eval(text)))
except:
self.browser.append(
"%s is invalid!" % text)

因為Python預設都是處理unicode的字串,所以儘快把取得的字串轉為unicode, 是相當必要的一步!browser既然稱為browser, 自然可以接受html的指令,所以在這裡,我們可以看到有相關指令出現在輸出字串裡面. eval()用來判斷這字串是否有效,如果無效,就提出警示.

而最後,我們果然看到很短的main function...

沒有留言: