Table Of ContentRapid GUI Programming
with Python and Qt
Prentice Hall
Open Source Software Development Series
Arnold Robbins, Series Editor
“Real world code from real world applications”
Open Source technology has revolutionized the computing world. Many large-scale projects are in
production use worldwide, such as Apache, MySQL, and Postgres, with programmers writing applications
in a variety of languages including Perl, Python, and PHP. These technologies are in use on many different
systems, ranging from proprietary systems, to Linux systems, to traditional UNIX systems, to mainframes.
ThePrentice Hall Open Source Software Development Series is designed to bring you the best of these
Open Source technologies. Not only will you learn how to use them for your projects, but you will learn
from them. By seeing real code from real applications, you will learn the best practices of Open Source
developers the world over.
Titles currently in the series include:
Linux®Debugging and Performance Tuning SELinux by Example
Steve Best Frank Mayer, David Caplan, Karl MacMillan
0131492470, Paper, ©2006 0131963694, Paper, ©2007
The Defi nitive Guide to the Xen Hypervisor UNIX to Linux® Porting
David Chisnall Alfredo Mendoza, Chakarat Skawratananond,
013234971X, Hard, ©2008 Artis Walker
0131871099, Paper, ©2006
Understanding AJAX
Joshua Eichorn Rapid Web Applications with TurboGears
0132216353, Paper, ©2007 Mark Ramm, Kevin Dangoor, Gigi Sayfan
0132433885, Paper, © 2007
The Linux Programmer’s Toolbox
John Fusco Linux Programming by Example
0132198576, Paper, ©2007 Arnold Robbins
0131429647, Paper, ©2004
Embedded Linux Primer
Christopher Hallinan The Linux® Kernel Primer
0131679848, Paper, ©2007 Claudia Salzberg, Gordon Fischer,
Steven Smolski
The Apache Modules Book
0131181637, Paper, ©2006
Nick Kew
0132409674, Paper, © 2007 Rapid GUI Programming with Python and Qt
Mark Summerfi eld
0132354187, Hard, © 2008
New to the series: Digital Short Cuts
Short Cuts are short, concise, PDF documents designed specifi cally for busy technical professionals like
you. Each Short Cut is tightly focused on a specifi c technology or technical problem. Written by industry
experts and best selling authors, Short Cuts are published with you in mind — getting you the technical
information that you need — now.
Understanding AJAX: Debugging Embedded Linux
Consuming the Sent Data with XML and JSON Christopher Hallinan
Joshua Eichorn 0131580132, Adobe Acrobat PDF, © 2007
0132337932, Adobe Acrobat PDF, © 2007
Using BusyBox
Christopher Hallinan
0132335921, Adobe Acrobat PDF, © 2007
Rapid GUI Programming
with Python and Qt
The DefinitiveGuide to PyQt Programming
Mark Summerfield
UpperSaddleRiver,NJ·Boston·Indianapolis·SanFrancisco
NewYork·Toronto·Montreal·London·Munich·Paris·Madrid
Capetown·Sydney·Tokyo·Singapore·MexicoCity
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedas
trademarks. Wherethosedesignationsappearinthisbook,andthepublisherwasawareofatrademark
claim,thedesignationshavebeenprintedwithinitialcapitallettersorinallcapitals.
Theauthorandpublisherhavetakencareinthepreparationofthisbook,butmakenoexpressedorimplied
warrantyof anykindandassumenoresponsibilityforerrorsoromissions. Noliabilityisassumedfor
incidentalorconsequentialdamagesinconnectionwithorarisingoutof theuseof theinformationor
programscontainedherein.
Thepublisher offersexcellent discountson thisbook when orderedin quantityfor bulk purchasesor
specialsales,whichmayincludeelectronicversionsand/orcustomcoversandcontentparticulartoyour
business,traininggoals,marketingfocus,andbrandinginterests. Formoreinformation,pleasecontact:
U.S.CorporateandGovernmentSales
(800)382-3419
corpsales@pearsontechgroup.com
ForsalesoutsidetheUnitedStates,pleasecontact:
InternationalSales
international@pearsoned.com
VisitusontheWeb: www.prenhallprofessional.com
Libraryof CongressCataloging-in-PublicationData
Summerfield,Mark
RapidGUIprogrammingwithPythonandQt:thedefinitiveguidetoPyQtprogramming/Mark
Summerfield.
p. cm.
Includesbibliographicalreferencesandindex.
ISBN978-0-13-235418-9 (hardcover:alk. paper)
1. Qt(Electronicresource) 2. Graphicaluserinterfaces(Computersystems) 3. Python(Computer
programlanguage) I. Title.
QA76.9.U83S892007
005.1’2—dc22
2007034852
Copyright©2008PearsonEducation,Inc.
Allrightsreserved. PrintedintheUnitedStatesofAmerica.
Trolltech®,Qt®andtheTrolltechlogoareregisteredtrademarksofTrolltechASA.
ISBN-13: 978-0-13-235418-9
ISBN-10: 0-13-235418-7
TextprintedintheUnitedStatesonrecycledpaperatEdwardsBrothersinAnnArbor,Michigan.
Firstprinting,October2007
Thisbook isdedicatedto
Andrea Summerfield
This page intentionally left blank
Contents
Foreword ......................................................... xiii
Introduction ...................................................... 1
PartI: Python Programming
Chapter1. DataTypesandDataStructures ..................... 9
ExecutingPythonCode ......................................... 10
VariablesandObjects ........................................... 12
NumbersandStrings ........................................... 15
IntegersandLongIntegers ................................. 16
FloatsandDecimals ........................................ 17
Bytestrings,UnicodeStrings,andQStrings .................. 20
Collections ..................................................... 29
Tuples ..................................................... 29
Lists....................................................... 31
Dictionaries................................................ 35
Sets ....................................................... 37
Built-inFunctions .............................................. 37
Summary ...................................................... 41
Exercises ...................................................... 42
Chapter2. ControlStructures ................................... 45
ConditionalBranching.......................................... 46
Looping ........................................................ 49
ListComprehensionsandGenerators ....................... 53
Functions ...................................................... 55
GeneratorFunctions ....................................... 58
UsingKeywordArguments ................................. 59
LambdaFunctions ......................................... 61
DynamicFunctionCreation ................................ 62
PartialFunctionApplication ................................ 63
ExceptionHandling ............................................ 66
vii
Summary ...................................................... 72
Exercises ...................................................... 72
Chapter3. ClassesandModules ................................. 75
CreatingInstances ............................................. 77
MethodsandSpecialMethods ................................... 79
StaticData,andStaticMethodsandDecorators ............. 85
Example:TheLengthClass ................................. 86
CollectionClasses .......................................... 92
Example:TheOrderedDictClass ............................ 92
InheritanceandPolymorphism.................................. 99
ModulesandMultifileApplications .............................. 104
UsingthedoctestModule ................................... 105
Summary ...................................................... 107
Exercises ...................................................... 108
PartII: Basic GUI Programming
Chapter4. IntroductiontoGUIProgramming .................. 111
APop-UpAlertin25Lines ...................................... 112
AnExpressionEvaluatorin30Lines ............................ 116
ACurrencyConverterin70Lines ............................... 121
SignalsandSlots ............................................... 127
Summary ...................................................... 136
Exercise ....................................................... 137
Chapter5. Dialogs ............................................... 139
DumbDialogs .................................................. 141
StandardDialogs ............................................... 147
ModalOK/Cancel-StyleDialogs ............................. 148
SmartDialogs .................................................. 154
ModelessApply/Close-StyleDialogs ......................... 155
Modeless“Live”Dialogs .................................... 159
Summary ...................................................... 162
Exercise ....................................................... 163
Chapter6. MainWindows........................................ 165
CreatingaMainWindow ....................................... 166
ActionsandKeySequences ................................. 171
ResourceFiles ............................................. 172
viii
CreatingandUsingActions................................. 174
RestoringandSavingtheMainWindow’sState .............. 181
HandlingUserActions ......................................... 190
HandlingFileActions ...................................... 191
HandlingEditActions ...................................... 197
HandlingHelpActions ..................................... 200
Summary ...................................................... 201
Exercise ....................................................... 202
Chapter7. UsingQtDesigner .................................... 205
DesigningUserInterfaces ...................................... 208
ImplementingDialogs .......................................... 216
TestingDialogs................................................. 221
Summary ...................................................... 223
Exercise ....................................................... 224
Chapter8. DataHandlingandCustomFileFormats............ 227
MainWindowResponsibilities .................................. 229
DataContainerResponsibilities................................. 235
SavingandLoadingBinaryFiles ................................ 240
WritingandReadingUsingQDataStream................... 240
WritingandReadingUsingthepickleModule ............... 246
SavingandLoadingTextFiles .................................. 249
WritingandReadingUsingQTextStream ................... 250
WritingandReadingUsingthecodecsModule ............... 255
SavingandLoadingXMLFiles.................................. 256
WritingXML .............................................. 256
ReadingandParsingXMLwithPyQt’sDOMClasses ........ 259
ReadingandParsingXMLwithPyQt’sSAXClasses ......... 262
Summary ...................................................... 265
Exercise ....................................................... 266
PartIII: Intermediate GUI Programming
Chapter9. LayoutsandMultipleDocuments.................... 269
LayoutPolicies ................................................. 270
TabWidgetsandStackedWidgets ............................... 272
ExtensionDialogs .......................................... 276
Splitters ....................................................... 280
SingleDocumentInterface(SDI) ................................ 283
ix
Description:Linux Programming by Example. Arnold Robbins Short Cuts are short, concise, PDF documents designed specifically for busy technical professionals like you. Each Short Cut is tightly Rapid GUI programming with Python and Qt : the definitive guide to PyQt programming / Mark. Summerfield. p. cm.