GUI Programming with Python QT Edition Boudewijn Rempt instant download
GUI Programming with Python QT Edition Boudewijn Rempt instant download
https://ebookname.com/product/gui-programming-with-python-qt-
edition-boudewijn-rempt/
https://ebookname.com/product/rapid-gui-programming-with-python-
and-qt-1st-edition-mark-summerfield/
https://ebookname.com/product/programming-arcgis-with-python-
cookbook-2nd-edition-eric-pimpler/
https://ebookname.com/product/game-programming-with-python-game-
development-series-1st-edition-riley/
https://ebookname.com/product/empire-of-ancient-egypt-wendy-
christensen/
The Atmosphere and Ocean A Physical Introduction Third
Edition Neil C. Wells(Auth.)
https://ebookname.com/product/the-atmosphere-and-ocean-a-
physical-introduction-third-edition-neil-c-wellsauth/
https://ebookname.com/product/global-health-watch-3-an-
alternative-world-health-report-3rd-edition-amit-sengupta/
https://ebookname.com/product/all-s-well-that-ends-well-webster-
s-french-thesaurus-edition-william-shakespeare/
https://ebookname.com/product/irish-politics-and-social-conflict-
in-the-age-of-the-american-revolution-1st-edition-maurice-r-
oconnell/
https://ebookname.com/product/self-healing-composites-shape-
memory-polymer-based-structures-1st-edition-guoqiang-li/
Encyclopedia of law enforcement 1st Edition Larry E.
Sullivan
https://ebookname.com/product/encyclopedia-of-law-
enforcement-1st-edition-larry-e-sullivan/
GUI Programming with Python:
QT Edition
Boudewijn Rempt
GUI Programming with Python: QT Edition
by Boudewijn Rempt
Copyright (c) 2001 by Command Prompt, Inc. This material may be distributed only subject to the terms and
conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at
http://www.opencontent.org/openpub/).
‘Distribution of substantively modified versions of this document is prohibited without the explicit permission of the
copyright holder.’ to the license reference or copy.
‘Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior
permission is obtained from the copyright holder.’ to the license reference or copy.
Although every reasonable effort has been made to incorporate accurate and useful information into this book, the
copyright holders make no representation about the suitability of this book or the information therein for any purpose.
It is provided “as is” without expressed or implied warranty.
Dedication
This book is dedicated to Irina.
6
Table of Contents
Preface.....................................................................................................................23
1. Who is using PyQt .......................................................................................24
2. For whom is this book intended...................................................................24
3. How to read this book ..................................................................................25
4. Conventions .................................................................................................26
5. Acknowledgments........................................................................................27
1. Introduction ........................................................................................................29
1.1. Python .......................................................................................................30
1.2. GUI programming with Python ................................................................33
1.3. About the BlackAdder IDE.......................................................................35
I. Introduction to the BlackAdder IDE................................................................37
2. Installation....................................................................................................39
2.1. Installing BlackAdder .......................................................................39
2.1.1. Windows ................................................................................39
2.1.2. Linux ......................................................................................40
2.2. Installing sip and PyQt without BlackAdder ....................................41
2.2.1. Building from source on Linux..............................................42
2.2.1.1. Problems with compilation .........................................43
2.2.2. Windows ................................................................................44
3. Interface .......................................................................................................47
3.1. Menubar ............................................................................................48
3.2. Toolbars.............................................................................................48
3.2.1. File toolbar .............................................................................49
3.2.2. Edit toolbar.............................................................................49
3.2.3. Execution toolbar ...................................................................49
3.2.4. Layout manager toolbar .........................................................50
3.2.5. Widgets ..................................................................................50
3.2.6. Help........................................................................................50
3.2.7. Pointer toolbar........................................................................50
3.2.8. More widget toolbars .............................................................51
3.3. Project management..........................................................................51
3.4. BlackAdder Configuration ................................................................53
3.5. Editing...............................................................................................55
3.6. Python shell.......................................................................................55
7
3.7. Conclusion ........................................................................................56
4. Introduction to Python .................................................................................57
4.1. Programming fundamentals ..............................................................57
4.2. The Rules ..........................................................................................61
4.2.1. Objects and references ...........................................................61
4.2.2. Formatting..............................................................................62
4.2.3. Keywords ...............................................................................63
4.2.4. Literals ...................................................................................64
4.2.5. Methods and functions...........................................................64
4.2.6. High level datatypes...............................................................65
4.3. Constructions ....................................................................................66
4.3.1. Looping ..................................................................................66
4.3.2. Branching...............................................................................69
4.3.3. Exceptions..............................................................................70
4.3.4. Classes....................................................................................71
4.4. Conclusion ........................................................................................72
5. Debugging....................................................................................................73
5.1. Running scripts .................................................................................76
5.2. Setting breakpoints............................................................................76
5.3. Stepping along ..................................................................................78
5.4. Debugging Techniques......................................................................81
5.4.1. Avoid changing your code .....................................................81
5.4.2. Gather data .............................................................................81
5.4.3. Minimal examples..................................................................82
5.5. If all else fails....................................................................................82
II. PyQt fundamentals ...........................................................................................85
6. Qt Concepts..................................................................................................87
6.1. Python, Qt and PyQt .........................................................................87
6.2. As simple as they come.....................................................................88
6.3. A better Hello World.........................................................................91
6.4. Designing forms................................................................................96
6.5. Conclusion ......................................................................................101
7. Signals and Slots in Depth .........................................................................103
7.1. The concept of signals and slots .....................................................103
7.1.1. Callbacks..............................................................................104
7.1.2. Action registry .....................................................................106
7.1.3. Signals and slots...................................................................108
8
7.2. Connecting with signals and slots...................................................110
7.3. Disconnecting .................................................................................120
7.4. A parser-formatter using signals and slots......................................127
7.5. Conclusion ......................................................................................137
8. String Objects in Python and Qt ................................................................139
8.1. Introduction.....................................................................................139
8.2. String conversions...........................................................................140
8.3. QCString — simple strings in PyQt ...............................................142
8.4. Unicode strings ...............................................................................146
8.4.1. Introduction to Unicode .......................................................147
8.4.2. Python and Unicode.............................................................148
8.4.2.1. String literals.............................................................149
8.4.2.2. Reading from files.....................................................151
8.4.2.3. Other ways of getting Unicode characters into Python
string objects ..................................................................153
8.4.3. Qt and Unicode ....................................................................156
9. Python Objects and Qt Objects ..................................................................159
9.1. Pointers and references ...................................................................159
9.2. Circular references ..........................................................................160
9.3. Qt objects, Python objects and shadow objects ..............................161
9.4. References and ownership ..............................................................163
9.5. Other C++ objects...........................................................................173
9.6. Connecting signals and slots...........................................................173
9.7. Object and class introspection ........................................................175
10. Qt Class Hierarchy...................................................................................177
10.1. Hierarchy.......................................................................................177
10.2. Base classes...................................................................................179
10.3. Application classes........................................................................182
10.3.1. Multiple document windows with QWorkspace................185
10.4. Widget foundations: QWidget ......................................................187
10.4.1. QColor................................................................................189
10.4.2. QPixmap, QBitmap and QImage .......................................190
10.4.3. QPainter .............................................................................191
10.4.4. QFont .................................................................................193
10.5. Basic widgets ................................................................................195
10.5.1. QFrame ..............................................................................197
10.5.2. QPushButton ......................................................................197
9
10.5.3. QLabel................................................................................199
10.5.4. QRadioButton ....................................................................202
10.5.5. QCheckBox........................................................................203
10.5.6. QListBox............................................................................204
10.5.7. QComboBox ......................................................................206
10.5.8. QLineEdit...........................................................................207
10.5.9. QMultiLineEdit..................................................................207
10.5.10. QPopupMenu ...................................................................207
10.5.11. QProgressBar ...................................................................207
10.5.12. QSlider and other small fry..............................................208
10.6. Advanced widgets .........................................................................209
10.6.1. QSimpleRichText, QTextView and QTextBrowser ...........209
10.6.2. QTextEdit ...........................................................................209
10.6.3. QListView and QListViewItem..........................................210
10.6.4. QIconView and QIconViewItem........................................211
10.6.5. QSplitter .............................................................................212
10.6.6. QCanvas, QCanvasView and QCanvasItems .....................212
10.6.7. QTable, QTableItem and QTableView (or QGridView).....213
10.7. Layout managers...........................................................................213
10.7.1. Widget sizing: QSizePolicy ...............................................215
10.7.2. Groups and frames .............................................................216
10.7.2.1. QHBox ....................................................................216
10.7.2.2. QVBox ....................................................................216
10.7.2.3. QGrid ......................................................................216
10.7.2.4. QGroupBox.............................................................216
10.7.3. QLayout .............................................................................217
10.7.4. QBoxLayout and children..................................................217
10.7.5. QGridLayout ......................................................................217
10.7.6. setGeometry .......................................................................220
10.8. Dialogs and Standard Dialogs.......................................................221
10.8.1. QDialog..............................................................................221
10.8.2. QMessageBox....................................................................221
10.8.3. QTabDialog........................................................................227
10.8.4. QWizard .............................................................................227
10.8.5. QFileDialog........................................................................227
10.8.6. QFontDialog ......................................................................228
10.8.7. QColorDialog.....................................................................229
10
10.8.8. QInputDialog .....................................................................230
10.8.9. QProgressDialog ................................................................230
10.9. Qt Utility classes and their Python equivalents ............................230
10.9.1. High level data structures...................................................235
10.9.2. Files and other IO...............................................................238
10.9.3. Date and time .....................................................................239
10.9.4. Mime ..................................................................................240
10.9.5. Text handling......................................................................241
10.9.6. Threads...............................................................................242
10.9.7. URL’s .................................................................................244
10.9.8. Qt modules that overlap with Python modules ..................245
11. Qt Designer, BlackAdder and uic ............................................................249
11.1. Introduction...................................................................................249
11.1.1. Starting out with the designer module ...............................249
11.1.2. Creating a design................................................................253
11.1.2.1. Grouping widgets....................................................253
11.1.2.2. Layout management................................................254
11.1.2.3. Tab order and accelerators ......................................254
11.2. Advanced Designer topics ............................................................256
11.2.1. Defining signals and slots in Designer...............................256
11.2.2. Adding your own widgets ..................................................259
11.2.3. Layout management...........................................................262
11.2.3.1. The Horizontal Layout Manager.............................264
11.2.3.2. The Vertical Layout Manager .................................264
11.2.3.3. The Grid Layout Manager ......................................264
11.2.3.4. The Spacer object....................................................265
11.2.3.5. What widgets can do to get the space they want.....265
11.2.3.6. Creating a complex form ........................................266
11.2.4. Generating and using Python code with pyuic ..................268
11.2.5. Generating C++ code with uic ...........................................270
III. Creating real applications with PyQt ..........................................................273
12. Application Frameworks..........................................................................275
12.1. Architecture: models, documents and views.................................275
12.1.1. A document-view framework ............................................277
12.2. Macro languages ...........................................................................284
12.3. Project layout ................................................................................284
13. Actions: menus, toolbars and accelerators...............................................287
11
13.1. Actions ..........................................................................................287
13.2. Menus............................................................................................291
13.3. Toolbars.........................................................................................292
13.4. Keyboard accelerators...................................................................294
13.5. Setting an application icon............................................................295
14. Automatic testing with PyUnit ................................................................297
14.1. About unittests ..............................................................................297
14.2. Starting out....................................................................................299
14.3. A first testcase ...............................................................................300
14.4. Collecting tests in a test suite........................................................302
14.5. A more complicated test ...............................................................303
14.6. Large projects................................................................................306
14.7. Testing signals and slots................................................................309
14.8. Conclusion ....................................................................................312
15. A More Complex Framework: Multiple Documents, Multiple Views ....315
15.1. Introduction...................................................................................315
15.2. Document/View Manager .............................................................319
15.3. The Document Manager ...............................................................325
15.4. Document......................................................................................332
15.5. View ..............................................................................................334
15.6. The actual application ...................................................................335
15.7. Conclusion ....................................................................................348
16. User Interface Paradigms .........................................................................349
16.1. Tabbed documents ........................................................................349
16.2. Back to the MDI windows ............................................................353
16.3. A row of split windows.................................................................354
16.4. A stack of documents....................................................................355
16.5. A more complex view management solution................................357
16.6. Conclusion ....................................................................................360
17. Creating Application Functionality..........................................................363
17.1. Introduction...................................................................................363
17.1.1. Giving the project a name ..................................................363
17.2. The view........................................................................................363
17.3. The document................................................................................368
17.4. Saving and loading documents .....................................................370
17.4.1. Loading ..............................................................................370
17.4.2. Saving ................................................................................371
12
17.5. Undo, redo and other editing functions.........................................372
17.6. Conclusion ....................................................................................378
18. Application Configuration .......................................................................379
18.1. Platform differences......................................................................379
18.2. The Python way of handling configuration settings .....................380
18.3. Implementing configurations settings for Kalam..........................381
18.3.1. Handling configuration data in your application ...............381
18.3.2. Saving and loading the configuration data.........................384
18.3.3. Using configuration data from the application...................386
18.3.3.1. Font settings ............................................................387
18.3.3.2. Window geometry ...................................................387
18.3.3.3. Determining the widget style ..................................389
18.3.3.4. Setting the viewmanager.........................................391
18.3.4. Catching the changes when the application closes ............393
18.4. Settings in Qt 3.0 ..........................................................................394
18.5. Conclusion ....................................................................................397
19. Using Dialog Windows ............................................................................399
19.1. Modal: a preferences dialog..........................................................399
19.1.1. Designing the dialog ..........................................................399
19.1.2. Creating the settings dialog window..................................401
19.1.3. Calling the settings dialog window....................................412
19.2. Non-modal: Search and replace ....................................................418
19.2.1. Design ................................................................................418
19.2.2. Integration in the application .............................................419
19.2.3. Implementation of the functionality...................................422
19.3. Conclusion ....................................................................................435
20. A Macro Language for Kalam .................................................................437
20.1. Executing Python code from Python ............................................437
20.1.1. Playing with eval() .........................................................439
20.1.2. Playing with exec..............................................................440
20.1.3. Playing with execfile() .................................................442
20.2. Integrating macros with a GUI .....................................................443
20.2.1. Executing the contents of a document ...............................443
20.2.2. startup macros ....................................................................452
20.3. Creating a macro API from an application ...................................453
20.3.1. Accessing the application itself .........................................454
20.3.2. Accessing application data.................................................456
13
20.3.3. Accessing and extending the GUI......................................456
20.3.4. Kalam rivals Emacs: an Eliza macro .................................457
20.4. Conclusion ....................................................................................460
21. Drawing on Painters and Canvases ..........................................................461
21.1. Working with painters and paint devices ......................................461
21.1.1. A painting example ............................................................462
21.2. QCanvas ........................................................................................471
21.2.1. A simple Unicode character picker....................................473
21.2.1.1. The canvas...............................................................476
21.2.1.2. The view on the canvas ...........................................478
21.2.1.3. Tying the canvas and view together ........................480
21.3. Conclusion ....................................................................................484
22. Gui Design in the Baroque Age ...............................................................485
22.1. Types of gui customization ...........................................................485
22.2. Faking it with bitmaps ..................................................................486
22.3. Creating themes with QStyle ........................................................491
22.3.1. Designing the style.............................................................491
22.3.2. Setting up ...........................................................................492
22.3.3. A Qt 2 custom style............................................................493
22.3.4. Using styles from PyQt......................................................505
23. Drag and drop ..........................................................................................521
23.1. Handling drops..............................................................................521
23.2. Initiating drags ..............................................................................523
23.3. Conclusion ....................................................................................525
24. Printing.....................................................................................................527
24.1. The QPrinter class .....................................................................527
24.2. Adding printing to Kalam .............................................................528
24.3. Putting ink to paper.......................................................................530
24.4. Conclusion ....................................................................................531
25. Internationalizing an Application ............................................................533
25.1. Translating screen texts.................................................................533
26. Delivering your Application ....................................................................541
26.1. Introduction...................................................................................541
26.2. Packaging source ..........................................................................542
26.3. Starting with distutils. ...................................................................544
26.3.1. setup.py ..............................................................................544
26.3.2. MANIFEST.in....................................................................546
14
26.3.3. setup.cfg .............................................................................547
26.3.4. Creating the source distribution .........................................547
26.3.5. Installing a source archive..................................................550
26.4. Creating Unix RPM packages.......................................................550
26.5. Windows installers ........................................................................551
26.6. Desktop integration .......................................................................552
27. Envoi ........................................................................................................553
IV. Appendices .....................................................................................................555
A. Reading the Qt Documentation.................................................................557
B. PyQwt: Python Bindings for Qwt .............................................................563
B.1. NumPy............................................................................................563
B.2. PyQwt.............................................................................................568
C. First Steps with Sip ...................................................................................573
C.1. Introduction ....................................................................................573
C.2. How sip works................................................................................574
C.3. Creating .sip files............................................................................574
C.4. Things sip can’t do automatically ..................................................577
C.4.1. Handwritten code ................................................................577
C.4.2. Other limitations..................................................................580
C.5. Where to look to start writing your own wrappers/bindings..........580
C.6. Sip usage and syntax ......................................................................581
C.6.1. Usage...................................................................................581
C.6.1.1. Invocation, Command Line ......................................581
C.6.1.2. Limitations ...............................................................582
C.6.1.3. Files ..........................................................................582
C.6.1.3.1. Source Files ...................................................582
C.6.1.3.2. Files containing the wrapping .......................582
C.6.1.3.3. Intermediate Files..........................................583
C.6.1.3.4. Auxilliary Files..............................................584
C.6.1.4. .sip File Syntax.........................................................585
C.6.1.4.1. General rules .................................................585
C.6.1.4.2. Macros...........................................................585
C.7. Directives........................................................................................586
C.7.1. Documentation ....................................................................586
%Copying ..............................................................................586
%Doc......................................................................................587
%ExportedDoc.......................................................................587
15
C.7.2. Modules...............................................................................588
%Module................................................................................588
%Include ................................................................................589
%Import .................................................................................590
C.7.3. Conditional Elements ..........................................................590
%If..........................................................................................591
%End......................................................................................591
Version().................................................................................592
%Version ................................................................................593
%PrimaryVersions..................................................................594
%VersionCode........................................................................594
C.7.4. C++ and Header Code Sections ..........................................595
%HeaderCode ........................................................................595
%ExportedHeaderCode..........................................................596
%ExposeFunction ..................................................................596
%C++Code.............................................................................597
%MemberCode ......................................................................597
%VirtualCode.........................................................................598
%VariableCode ......................................................................598
C.7.5. Python Code Sections .........................................................599
%PythonCode ........................................................................599
%PrePythonCode ...................................................................599
C.7.6. Mapped Classes...................................................................600
%ConvertFromClassCode......................................................600
%ConvertToClassCode ..........................................................601
%CanConvertToClassCode....................................................601
%ConvertToSubClassCode ....................................................602
C.7.7. Special Python methods ......................................................602
PyMethods .............................................................................603
PyNumberMethods ................................................................604
PySequenceMethods ..............................................................604
PyMappingMethods...............................................................605
C.7.8. Other....................................................................................606
%Makefile ..............................................................................606
C.8. Accepted C++ / Qt constructs ........................................................606
C.9. SIPLIB Functions...........................................................................609
C.9.1. Public Support Functions ....................................................609
16
C.9.2. Information functions..........................................................609
sipGetCppPtr..........................................................................610
sipGetComplexCppPtr ...........................................................610
sipGetThisWrapper ................................................................611
sipIsSubClassInstance............................................................612
C.9.3. Conversions and argument parsing .....................................613
sipParseArgs...........................................................................614
sipConvertToCpp ...................................................................617
sipMapCppToSelf ..................................................................618
sipConvertToVoidPtr ..............................................................619
sipConvertFromVoidPtr .........................................................620
sipConvertFromBool..............................................................621
sipCheckNone ........................................................................622
sipBadVirtualResultType .......................................................623
sipBadSetType .......................................................................624
C.9.4. Ressource handling .............................................................625
sipReleaseLock ......................................................................625
sipAcquireLock......................................................................625
sipCondReleaseLock..............................................................626
sipCondAcquireLock .............................................................627
sipMalloc................................................................................628
sipFree....................................................................................629
C.9.5. Calling Python.....................................................................629
sipEvalMethod .......................................................................630
sipCallHook ...........................................................................630
C.9.6. Functions specifically for signals/slots................................631
sipEmitSignal.........................................................................631
sipConvertRx .........................................................................632
sipConnectRx.........................................................................634
sipGetRx ................................................................................635
sipDisconnectRx ....................................................................636
C.9.7. Private Functions .................................................................638
Bibliography .........................................................................................................639
17
18
List of Tables
1-1. GUI Toolkits for Python ...................................................................................33
7-1. Matrix of QObject.connect() combinations..............................................119
10-1. Qt and Python high-level datastructures.......................................................235
10-2. Qt and Python network classes.....................................................................245
C-1. C++ access specifiers and sip.........................................................................576
List of Figures
10-1. Qt Inheritance Hierarchy (only the most important classes) ........................177
10-2. Object Ownership Hierarchy ........................................................................179
20-1. Playing with eval() ....................................................................................439
20-2. Playing with exec ........................................................................................441
20-3. Playing with execfile() ...........................................................................442
List of Examples
1-1. Bootstrapping a Python application..................................................................31
6-1. hello1.py — hello world ...................................................................................89
6-2. hello2.py — a better hello world ......................................................................91
6-3. fragment from hello3.py ...................................................................................94
6-4. Fragment from hello5.py ..................................................................................94
6-5. Fragment from hello4.py ..................................................................................95
6-6. frmconnect.py ...................................................................................................97
6-7. dlgconnect.py — the subclass of the generated form .....................................100
7-1. A stupid button which is not reusable ............................................................103
7-2. A simple callback system ...............................................................................104
7-3. A central registry of connected widgets .........................................................106
7-4. Connecting a signal to a slot...........................................................................111
7-5. Connection a dial to a label with signals and slots .........................................113
7-6. Python signals and slots..................................................................................116
7-7. Python signals and slots with arguments ........................................................117
7-8. datasource.py — connecting and disconnecting signals and slots .................122
19
7-9. An XML parser with signals and slots ...........................................................128
8-1. qstring1.py — conversion from QString to a Python string.........................140
8-2. qstring2.py - second try of saving a QString to a file...................................141
8-3. empty.py - feeding zero bytes to a QCString..................................................143
8-4. null.py - empty and null QCStrings and Python strings .................................144
8-5. emptyqstring.py - feeding zero bytes to a QString .........................................146
8-6. Loading an utf-8 encoded text ........................................................................151
8-7. Building a string from single Unicode characters ..........................................153
8-10. uniqstring1.py - coercing Python strings into and from QStrings ................156
8-11. uniqstring2.py - coercing Python strings into and from QStrings ................157
9-1. refs.py - showing object references ................................................................160
9-2. circular.py - circululululular references..........................................................161
9-3. qtrefs1.py — about Qt reference counting .....................................................163
9-4. qtrefs2.py - keeping a Qt widget alive............................................................164
9-5. qtrefs3.py - Qt parents and children ...............................................................165
9-6. Eradicating a widget .......................................................................................166
9-7. children.py - getting the children from a single parent...................................167
9-8. Iterating over children.....................................................................................169
9-9. sigslot.py - a simple signals/slots implementation in Python, following the
Observer pattern.............................................................................................173
9-10. Object introspection using Qt .......................................................................175
9-11. Object introspection using Python................................................................176
10-1. event1.py - handling mouse events in PyQt..................................................180
10-2. action.py - Using a QAction to group data associated with user commands183
10-3. fragment from mdi.py - ten little scribbling windows..................................186
10-4. event2.py - using QWidget to create a custom, double-buffered drawing
widget.............................................................................................................187
10-5. snippet from event3.py - a peach puff drawing board ..................................190
10-6. fragment from action2.py - You cannot create a QPixmap before a
QApplication..................................................................................................192
10-7. buttons.py - Four pushbuttons saying ‘hello’. ..............................................198
10-8. label.py - a label associated with an edit control ..........................................199
10-9. radio.py - a group of mutually exclusive options .........................................202
10-10. listbox.py - A listbox where data can be associated with an entry .............204
10-11. tree.py - building a tree...............................................................................210
10-12. layout.py - two box layouts and adding and removing buttons dynamically to
a layout...........................................................................................................218
20
10-13. geometry.py - setting the initial size of an application ...............................220
10-14. dialogs.py - opening message and default dialogs boxes ...........................222
10-15. fragment from dialogs.py - opening a file dialog .......................................228
10-16. fragment from dialogs.py - opening a font dialog ......................................229
10-17. fragment from dialogs.py - opening a color dialog ....................................229
10-18. from dv_qt.py - using Qt utility classes......................................................231
10-19. fragment from db_python.py - using Python utility classes.......................233
10-20. Using QMimeSourceFactory (application.py)............................................241
10-21. thread1.py — Python threads without gui ..................................................242
10-22. Python threads and a PyQt gui window......................................................243
11-1. dlgcomplex.py — a subclass of frmcomplex.py ..........................................268
11-2. Setting default values....................................................................................270
12-1. A simple document-view framework ...........................................................277
12-2. Scripting an application is easy ....................................................................284
13-1. Defining a complex toggle action .................................................................288
15-1. A testcase for a document manager..............................................................319
15-2. The document manager class........................................................................325
15-3. The document class ......................................................................................332
15-4. The view class ..............................................................................................334
15-5. The application class ....................................................................................336
21-1. typometer.py - A silly type-o-meter that keeps a running count of how many
characters are added to a certain document and shows a chart of the typerate...
462
21-2. charmap.py - a Unicode character selection widget .....................................475
22-1. remote.py - remote control application.........................................................488
22-2. view.py - the main view of the remote control application ..........................489
22-3. button.py - the class that implements the pixmapped buttons ......................490
22-4. A Qt 2 custom style - a minimalist implementation of the classic Mac style in
PyQt. ..............................................................................................................493
22-5. Testing styles ................................................................................................506
23-1. Handling drop events....................................................................................521
23-2. Drag and drop ...............................................................................................524
25-1. Installing the translator .................................................................................538
26-1. README .....................................................................................................543
26-2. setup.py - a sample setup script ....................................................................544
26-3. MANIFEST.in ..............................................................................................546
C-1. Interface for QRegExp::match .......................................................................616
21
22
Preface
The main topic of this book is application development using PyQt, a library
extension to the Python programming language — a library that is meant to form
the basis for GUI programming. PyQt is free software, but there is also a
commercial IDE available, BlackAdder, that is specially written to assist working
with PyQt. I will show you the ins and outs of PyQt by developing a complete and
complex application.
Like most thirty–somethings who started programming in their teens, I’ve worked
with a lot of different technologies. I started with Sinclair Basic, going on to Turbo
Pascal and SNOBOL — I have developed for Windows in pure C, with Borland
Pascal and with Visual Basic. I’ve done my stretch with Oracle Forms, and served
as a Java developer. On Linux, I’ve wet my feet with Free Pascal, with C++, using
XForms and Qt. And just when I was getting fond of Qt and C++, I found out about
Python — a few years ago now. I found programming with PyQt to be a lot more
fun than anything else, and productive fun, too.
For sheer productivity, nothing beats Python and PyQt. And while there’s always
something new to learn or explore in Python, if you’re in the mood, it’s easy and
pleasant to write useful applications from the first day. No other programming
language or library has ever given me that.
So, when Cameron Laird, during a discussion on the comp.lang.python newsgroup
suggested that I’d write a book on this particular way of developing GUI
applications with Python, I started to think — and more than think. I started to
contact publishers, until one day Shawn Gordon of TheKompany brought me into
contact with Joshua Drake of Opendocs. I started writing text and code almost
immediately.
Joshua’s patience has been monumental — I should have written this book between
February and May, but it took me until November. All I can say for myself is that a
lot of effort has gone into the book. I discuss most of the concepts and classes of the
Qt library, which might be useful not only to Python developers, but also to C++
developers, and I have written a lot of example scripts.
Where Bruce Eckel (of Thinking in Java fame) favors small example programs
because they clearly illustrate the matter in hand, John Grayson in Python and
Tkinter argues that larger real-life applications are more useful because they don’t
23
Preface
24
Preface
your chosen language is Python. The same holds for the extensive html
documentation that comes with the C++ Qt library.
With the growing popularity of Python, PyQt and BlackAdder, people will start
using these tools who don’t want to translate C++ to Python to figure out what they
are supposed to do.
This is the first group of people for whom I’ve written this book: beginning software
developers who have chosen Python because it allows them to become productive
quickly with a language and an environment that have been designed to
accommodate ‘subject specialists’. That is, people who need to get an application
done to help them with their work, but who are not developers by profession.
Then there are the experienced developers, people who have been coding in Visual
Basic, Delphi or Java, and who, like the first group, now need something a lot more
productive and portable. They will be able to grasp the concepts quickly, but may
find a lot of use in the advanced code examples and the in-depth discussion of issues
particular to PyQt.
Another group of possible readers consists of C++ developers who have turned to
Python as a rapid prototyping language. Prototyping with the same GUI library they
will use for their final C++ application will give them a definite advantage, as most
of the prototype code will remain useful.
Finally there are people who are more experienced in Python than I am, but who
want to get acquainted with one of the best-designed GUI toolkits available for the
language—there is a lot of interesting content to be found in this book for them, too.
My aim in writing this book was to create a genuine vademecum for Python, PyQt
and GUI programming. If you keep referring to this book a year after you’ve
acquired it, if you can find the answer to most of your daily and quite a few of your
exceptional problems, and if you tend to keep this book in the vicinity of your desk,
then I will have succeeded.
25
Another Random Document on
Scribd Without Any Related Topics
shall find, that in different animals, nature operates in different
ways, in order to produce the same general end.
The human female, and the female of quadrupeds, are possessed of
a temperate cherishing warmth; this fits them for easy gestation,
and enables them to afford proper nourishment to their young, till
the time of birth.
Birds are intended to soar in the air, or to flit from place to place in
search of food. Gestation, therefore, would be burdensome to them.
For this reason, they lay eggs, covered with a hard shell: these, by
natural instinct, they sit upon, and cherish till the young be
excluded. The ostrich and the cassowary are said to be exempt from
this law; as they commit their eggs to the sand, where the intense
heat of the sun hatches them.
Fishes inhabit the waters, and most of them have cold blood, unfit
for nourishing their young. The all-wise Creator, therefore, has
ordained that most of them should lay their eggs near the shore;
where, by means of the solar rays, the water is warmer, and also
fitter for that purpose; and also because water insects abound more
there, which afford nourishment to the young fry.
Salmon, when they are about to deposit their eggs, are led by
instinct to ascend the stream, where purity and freshness are to be
found in the waters: and to procure such a situation for its young,
this fish will endure incredible toil and hazard.
The butterfly-fish is an exception to this general law, for that brings
forth its young alive. The species of fish whose residence is in the
middle of the ocean, are also exempt. Providence has given to these,
eggs that swim; so that they are hatched among the sea-weeds,
which also swim on the surface.
The various kinds of whales have warm blood, and therefore bring
forth their young alive, and suckle them with their teats.
Some amphibious animals also bring forth their young alive, as the
viper, &c. But such species as lay eggs, deposit them in places where
the heat of the sun supplies the want of warmth in the parent. Thus
the frog, and the lizard, drop their’s in shallow waters, which soon
receive a genial heat by the rays of the sun; the common snake, in
dunghills, or other warm places. The crocodile and sea-tortoise go
ashore to lay their eggs in the sand; in these cases, Nature, as a
provident nurse, takes care of all.
The multiplication of animals is not restrained to the same rule in all;
for some have a remarkable power of increase, while others are, in
this respect, confined within very narrow limits. Yet, in general, we
find, that nature observes this order, that the least animals, and
those which are most useful for food to others, usually increase with
the greatest rapidity. The mite, and many other insects, will multiply
to a thousand within the compass of a few days; while the elephant
hardly produces a young one in two years.
Birds of the hawk-kind seldom lay more than two eggs; while poultry
will produce from fifteen to thirty. The diver, or loon, which is eaten
by few animals, lays also only two eggs; but the duck-kind, moor
game, partridges, &c. and small birds in general, lay a great many.
Most of the insect tribes neither bear young nor hatch eggs; yet they
are the most numerous of all living creatures; and were their bulk
proportionable to their numbers, there would not be room on the
earth for any other animals. The Creator has wisely ordained the
preservation of these minute creatures. The females lay not their
eggs indiscriminately, but are endued with instinct to choose such
places as may supply their infant offspring with proper nourishment:
in their case, this is absolutely necessary, for the mother dies as
soon as she has deposited her eggs, the male parent having died
before this event takes place; so that no parental care ever falls to
the lot of this orphan race. And indeed, were the parents to live, it
does not appear that they would possess any power to assist their
young. Butterflies, weevils, tree-bugs, gall-insects, and many others,
lay their eggs on the leaves of plants; and every different tribe
chooses its own species of plants. Nay, there is scarce any plant
which does not afford nourishment to some insect; and still more,
there is hardly any part of a plant which is not preferred by some of
them. Thus one feeds upon the flower; another upon the leaves;
another upon the trunk; and still another upon the root. But it is
particularly curious to observe how the leaves of some trees of
plants are formed into dwellings for the convenience of these
creatures. Thus the gall-insect, fixes her eggs in the leaves of an
oak; the wounded leaf swells, and a knob arises like an apple, which
includes, protects, and nourishes the embryo. In the same manner
are the galls produced, which are brought from Asiatic Turkey, and
which are used both as a medicine, and as a dye in several of our
manufactories.
When the tree-bug has deposited its eggs in the boughs of the fir-
tree, excrescences arise, shaped like pearls. When another insect of
the same species has deposited its eggs in the mouse-ear, chick-
weed, or speedwell plants, the leaves contract in a wonderful
manner into the shape of a head. The water spider excludes eggs
either on the extremities of juniper, which from thence forms a
lodging that resembles the arrow-headed grass; or on the leaves of
the poplar, from whence a red globe is produced. The tree-louse lays
its eggs on the leaves of the black poplar, which turn into a kind of
inflated bag; and so in many other instances.
Nor is it only upon plants that insects live and lay their eggs. The
gnat commits her’s to stagnant waters; the flesh-fly, in putrified
flesh; another kind of insect deposits her’s in the cracks of cheese.
Some insects exclude their eggs on certain animals; the mill-beetle,
between the scales of fishes; a species of the gadfly, on the back of
bullocks; another of the same species, on the back of the rein-deer;
another, in the noses of sheep; another still, in the intestinal tube, or
the throat of horses. Nay, even insects themselves are generally
surrounded with the eggs of other insects; so that there is, perhaps,
no animal to be found, but what affords both lodging, and
nourishment, and food, to other animals: even man himself, the
haughty lord of this lower world, is not exempt from this general
law.
It would not be consistent with the plan of this work to embrace the
whole natural history of the animal and vegetable kingdom. This is a
Book of Curiosities; and it is our intention to present the reader with
a sketch of the most remarkable things in the universe: our present
subject, therefore, being curiosities respecting animals, we shall
commence with—
The Beaver.—This animal was known to the ancients for its
possession of that sebaceous matter called castor, secreted by two
large glands near its genitals and anus, and of which each animal
has about two ounces; but they appear to have been unacquainted
with its habits and economy, with that mental contrivance and
practical dexterity, which in its natural state so strikingly distinguish
it. Beavers are found in the most northern latitudes of Europe and
Asia, but are most abundant in North America.
In the months of June and July, they assemble in large companies to
the number of two hundred, on the banks of some water, and
proceed to the formation of their establishment. If the water be
subject to risings and fallings, they erect a dam, to preserve it at a
constant level; where this level is naturally preserved, this labour is
superseded. The length of this dam is occasionally eight feet. In the
preparation of it, they begin with felling some very high, but not
extremely thick tree, on the border of a river, which can be made to
fall into the water; and, in a short time, this is effected by the united
operation of many, with their fore-teeth, the branches being
afterwards cleared by the same process. A multitude of smaller trees
are found necessary to complete the fabric, and many of these are
dragged from some distance by land, and formed into stakes; the
fixing of which is a work of extreme difficulty and perseverance,
some of the beavers with their teeth raising their large ends against
the crossbeam, while others at the bottom dig with their fore-feet
the holes in which the points are to be sunk. A series of these
stakes, in several rows, is established from one bank of the river to
the other, in connection with the cross-tree, and the intervals
between them are filled up by vast quantities of earth, brought from
a distance, and plashed with materials adapted to give it tenacity,
and prevent its being carried off. The bark is formed at the bottom,
of about the width of twelve feet, diminishing as it approaches the
surface of the water, to two or three; being thus judiciously
constructed to resist its weight and efforts by the inclined plane
instead of perpendicular opposition.
These preparations, of such immense magnitude and toil, being
completed, they proceed to the construction of their mansions,
which are raised on piles near the margin of the stream or lake, and
have one opening from the land, and another by which they have
instant access to the water. These buildings are usually of an
orbicular form, in general about the diameter of ten feet, and
comprehending frequently several stories. The foundation walls are
nearly two feet in thickness, resting upon planks or stakes, which
constitute also their floors. In the houses of one story only, the
walls, which in all cases are plastered with extreme neatness both
externally and within, after rising about two feet perpendicularly,
approach each other, so as at length to constitute, in closing, a
species of dome. In the application of the mortar to their
habitations, the tails as well as feet of the beavers are of essential
service. Stone, wood, and a sandy kind of earth, are employed in
their structures, which, by their compactness and strength,
completely preclude injury from winds and rain. The alder, poplar,
and willow, are the principal trees which they employ; and they
always begin their operations on the trunk, at nearly two feet above
the ground; nor do they ever desist from the process till its fall is
completed. They sit instead of stand, at this labour, and while
reducing the tree to the ground, derive a pleasure at once from the
success of their toils, and from the gratification of their palate and
appetite by the bark, which is a favourite species of food to them, as
well as the young and tender parts of the wood itself.
For their support in winter, ample stores are laid up near each
separate cabin; and occasionally to give variety and luxury to their
repasts during a long season, in which their stores must have
become dry and nearly tasteless, they will make excursions into the
neighbouring woods for fresh supplies. Depredations by the tenants
of one cabin on the magazines of another are unknown, and the
strictest notions of property and honesty are universal. Some of their
habitations will contain six only, others twelve, and some even
twenty or thirty inhabitants; and the whole village or township
contains in general about twelve or fourteen habitations. Strangers
are not permitted to intrude on the vicinity; but, amidst the different
members of the society itself, there appears to prevail that
attachment and that friendship which are the natural result of
mutual co-operation, and of active and successful struggles against
difficulty. The approach of danger is announced by the violent
striking of their tails against the surface of the water, which extends
the alarm to a great distance; and, while some throw themselves for
security into the water, others retire within the precincts of their
cabins, where they are safe from every enemy but man.
The neatness as well as the security of their dwellings is remarkable,
the floors being strewed over with box and fir, and displaying the
most admirable cleanness and order. Their general position is that of
sitting, the upper part of the body, with the head, being considerably
raised, while the lower touches, and is somewhat indeed immersed
in, the water. This element is not only indispensable to them in the
same way as to other quadrupeds, but they carefully preserve
access to it even when the ice is of very considerable depth, for the
purpose of regaling themselves by excursions to a great extent
under the frozen surface. The most general method of taking them
is by attacking their cabins during these rambles, and watching their
approach to a hole dug in the ice at a small distance, to which they
are obliged, after a certain time, to resort for respiration.
If a man, who had never been informed of the industry of beavers
and their manner of building, were shewn the edifices that they
construct, he would suppose them to be the work of most eminent
architects. Every thing is wonderful in the labours of these
amphibious animals; the regular plan, the size, the solidity, and the
admirable art of these buildings, must fill every attentive observer
with astonishment.
The works of beavers have a great resemblance to those of men;
and upon their first appearance we may imagine them to be
produced by rational and thinking beings; but when we examine
them nearer, we shall find that in all their proceedings, these animals
do not act upon the principles of reason, but by an instinct which is
implanted in them by nature. If reason guided their labours, we
should naturally conclude that the buildings which they now
construct would be very different from those they formerly made,
and that they would gradually advance towards perfection. But we
find that they never vary in the least from the rules of their
forefathers, never deviate from the circle prescribed to them by
nature, and the beavers of to-day build exactly after the same plan
as those which lived before the deluge. But they are not the less
worthy of our admiration. In these sagacious creatures we have an
example of the great diversity there is in the instinct of animals—
how superior is the instinct of the beaver to that of the sheep!
The flesh of the anterior part of the bodies of beavers resembles
that of land animals in substance and flavour; while that of the lower
possesses the taste, and smell, and lightness of fish.
The sexual union among these animals is connected with
considerable individual choice, sentiment, and constancy.—Every
couple pass together the autumn and winter, with the most perfect
comfort and affection. About the close of winter, the females, after a
gestation of four months, produce, in general, each two or three
young, and soon after this period they are quitted by the males, who
ramble into the country to enjoy the return of spring; occasionally
returning to their cabins, but no longer dwelling in them. When the
females have reared their young, which happens in the course of a
few weeks, to a state in which they can follow their dams, these also
quit their winter residence, and resort to the woods, to enjoy the
opening bloom and renovated supplies of nature. If their habitations
on the water should be impaired by floods, or winds, or enemies, the
beavers assemble with great rapidity to repair the damage. If no
alarm of this nature occurs, the summer is principally spent by them
in the woods, and on the advance of autumn they assemble in the
scene of their former labours and friendships, and prepare with
assiduity for the confinement and rigours of approaching winter.
When taken young, the beaver may be tamed without difficulty; but
it exhibits few or no indications of superior intelligence. Some
beavers are averse to that association which so strikingly
characterizes these animals in general, and satisfy themselves with
digging holes in the banks of rivers, instead of erecting elaborate
habitations. The fur of these is comparatively of little value.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookname.com