# Rapid GUI Programming with Python and Qt
# history:
# 2009/11/11 jzj create
from __future__ import division
"""
>>> print(1 / 2)
0.5
"""
import sys
import urllib2 # URL
from PyQt4.QtCore import *
from PyQt4.QtGui import *
# check python version
if sys.version_info[:2] < (2,4):
def sorted(items):
pass
# a customized partial function tool
def partial(func, arg):
def callme():
return func(arg)
return callme
# exception example
class SimplifyError(Exception):
pass
if not True:
raise SimplifyError, "Nothing to do"
# static data, inside class, ouside ansy def
class Balloon(object):
unique_colors = set() # static data
@staticmethod
def uniquecolor():
return len(Balloon.unique_colors)
# static method
# class method, first argument cls, which is class called on
# return by reference
def copy(self):
other = Balloon()
other.__amount = self.__amount
return other
# copy alternative # 1
def copy1(self):
import copy
return copy.copy(self)
# copy alternative # 2
def copy2(self):
return eval(repr(self))
# __attribute was name-mangle to _ClassName__attribute
class OrderedDict:
pass
dictionary = OrderedDict()
if isinstance(dictionary, OrderedDict):
pass
# generator
def itervalues(self):
for key in self.__keys:
yield self.__dict[key]
# test if iterable has title() method
items = []
try:
for item in items:
print item.title()
except AttributeError:
pass
for item in items:
if hasattr(item, "title") and callable(item.title):
print item.title()
# an interface(abstract base class)
def area(self):
raise NotImplementedError, "Dimension.area"
# decode argument
hours, mins = sys.argv[1].split(":")
message = " ".join(sys.argv[2:])
# sleep
import time
time.sleep(20)
# in PyQt, any widget can be used as a top-level window
# in PyQt, It's possible for us to connect not just to slots,
# but also to any callable
# A slot may not have more arguments than the signal that is connected to it, but may have less
# wrong usage of partial function in connect()
def __init__(self):
self.connect(button2, SIGNAL("clicked()"),
partial(self.anyButton, "Two"))
# right usage, duto special processing when lambda used to create
# wrappers in a connection
self.connect(button3, SIGNAL("clicked()"),
lambda who = "Three": self.anyButton(who))
# argument callback 1
self.button2callback = partial(self.anyButton, "Two")
self.connect(button2, SIGNAL("clicked()"),
self.button2callback)
# argument callback 2
self.button3callback = lambda who = "Three": self.anyButton(who)
self.connect(button3, SIGNAL("clicked()"),
self.button3callback)
# discover which QObject the invoking signal came from
def clicked(self):
button = self.sender()
if button is None or not isinstance(button, QPushButton):
return
# or
if not hasattr(button, "text"):
return
# stop signal
QObject.blockSignals()
# set Default button
buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
# regular expresion
QRegExp(r"[,;:.]")
# warning message box
QMessageBox.warning(self, "Format Error",
"The thousand seperator and the decimal marker"
"must be different.")
# unicode
thousands = unicode(self.thousandEdit.text())
# raise exception
raise DecimalError, ("The decimal marker may not be "
"empty.")
# dont't call super.accept(), call QDialog.accept() instead
# delete dialog when quit
self.setAttribute(Qt.WA_DeleteOnClose)
# post-mortem validation and preventative validataion
# get py file's path
os.path.dirname(__file__)
# add separator
separator = QAction(self)
separator.setSeparator(True)
# add context menu
self.imageLabel.setContextMenuPolicy(Qt.ActionsContextMenu)
# only run once, A timer event with a timeout of zero is taken to mean
# "do this when the event queue has nothing else to do"
QTimer.singleShot(0, self.loadInitialFile)
# open file in PyQt
fname = unicode("file".toString())
if fname and QFile.exists(fname):
self.loadFile(fname)
# restoreGeometry() dosn't work
QFileInfo.fileName()
# is equivalent to
os.path.basename()
# .ui -> .py
pyuic4 *.ui > *.py
dir = os.path.dirname(self.filename) \
if self.filename is no None else "."
|