GUI Programming With Python QT Edition Boudewijn Rempt Download PDF
GUI Programming With Python QT Edition Boudewijn Rempt Download PDF
com
https://ebookname.com/product/gui-programming-with-python-
qt-edition-boudewijn-rempt/
OR CLICK BUTTON
DOWLOAD NOW
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/programming-python-4th-edition-
mark-lutz/
Automate the Boring Stuff with Python Practical
Programming for Total Beginners 2nd Edition Al Sweigart
https://ebookname.com/product/automate-the-boring-stuff-with-
python-practical-programming-for-total-beginners-2nd-edition-al-
sweigart/
https://ebookname.com/product/programming-computer-vision-with-
python-tools-and-algorithms-for-analyzing-images-1st-edition-jan-
erik-solem/
https://ebookname.com/product/programming-in-python-3-a-complete-
introduction-to-the-python-language-2nd-edition-summerfield/
https://ebookname.com/product/python-interviews-discussions-with-
python-experts-1st-edition-mike-driscoll/
https://ebookname.com/product/python-programming-for-the-
absolute-beginner-3rd-edition-michael-dawson/
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
Preface
a small chapter that introduces programming with Python, in case you are not
already familiar with the language.
The second part deals with the concepts behind Python and PyQt. You don’t need to
read this part in order, but the chapters will give you a solid feel for the lay of the
land, and will enable you to find your way in the PyQt or Qt class documentation
(which is copious and excellent). Also, if you run into inexplicable behavior, you
might want to consult, for instance, the chapter on objects and references. The order
of the chapters doesn’t matter a whole lot.
Part three is where the real fun starts. From humble, but solid, beginnings, we will
build, chapter by chapter, a very real application. This part is probably best read in
order, but there are occasional excursional chapters that you might want to read
before anything else, such as the chapter on unit testing.
Finally, there are the appendices. Appendix A is useful if you don’t know anything
about C++, but still want to read the C++-based Qt documentation. The second
appendix, Appendix C, tells you how to wrap your own C++ extension libraries —
possibly based on Qt — using sip, the same tool that is used to create PyQt.
Appendix B deals with PyQwt and NumPy, an extension library for plotting and
graphic.
4. Conventions
Code is always printed in a monospaced font - like this:
class Test:
def printTest(self):
print self
This also holds for references to bits of code in the running text. If I cite a function
in the text, it is done like this: printTest() — i.e., I generally don’t quote the
parameter list. This makes it easier to follow the run of the text
Even though PyQt is a cross-platform toolkit (and I’ve tested most of the examples
on Windows, too), all development has been done on two Linux computers: my
laptop ‘maldar’, and my main system, ‘calcifer’, named after one of the main
characters in Diana Wynne Jones’ Howl’s Moving Castle. Because BlackAdder
26
Preface
wasn’t ready when I wrote this book, I used XEmacs and Bash (the command line
shell) to create and test all examples. That’s why you will often see prompts in
illustrations, and not so often screenshots of BlackAdder:
If you are using Windows, you can use a DOS box to emulate the Bash shell, but it
won’t be quite as convenient.
Finally, it is a widely-honored convention in programming literature, and especially
in Python books, to make allusions and puns that are related to the punny names of
the product. By rights I should have filled my code with witty allusions to the British
comedy series Monty Python and BlackAdder. However, excellent and essential as
these are, it’s been long years since I last watched those on the television, and I
don’t feel quite up to it. I’ve done my best, but don’t expect too much!
A note on versions: when I wrote this book I mostly used the stable 2.x versions of
Qt, but as soon as betas of Qt 3.x became available, I started integrating information
about its improvements in the text. I will note wherever one version is different
from the other. On the Opendocs webforum for this book you’ll find versions of the
examples both for Qt 2.x and Qt 3.x.
5. Acknowledgments
Writing a book started out fun, but it soon became far more work than I imagined.
My wife, Irina, and my children, Naomi, Rebecca and Menna were very patient
with me when I locked myself in the study day after day, night after night. But my
children have asked me never to write a book again. For now I’m inclined to agree,
but we’ll see.
Phil Thompson wrote the software that this book is all about — and has fixed bugs
faster than I could write chapters. Cameron Laird is responsible for egging me on to
start writing, and Shawn Gordon for introducing me to Joshua Drake, who dared to
27
Preface
take the book on. Michael Holloway, the editor, has fixed lots of bad English and
made this book a better book.
Neelakantan Krishmaswami is ultimately responsible for getting me to look at
Python at all — everyone needs someone else to help him over the
indentation-is-block-marking hurdle, and Neel helped me.
Jim Bublitz and Wilken Boie have contributed largely to Appendix C — Jim by
writing the introduction, and Wilken by writing the overview of directives. Gerard
Vermeulen wrote Appendix B. I’ve been editing their texts, though, so any mistakes
are mine. Cameron Laird gave persmission to use the graphics of a remote control
for Chapter 22. Bruce Sass took the time to explain about Debian packaging. Steve
Purcell helped with the chapter on unit-testing.
The following people have helped me learn about Python, Qt and the combination
in the past years, on the PyKDE mailing list (set up by Torsten Horstmann) and the
Python newsgroups: Aditya Bhambri, Albert Wagner, Anshul Shekhon, Arun
Sharma, Corrin Lakeland, David C. Morrill, David Eller, Deirdre Saoirse, Dirk
Reisnauer, Henning Schroeder, Johannes Sixt, Jonathan Perez, Karan Vasudeva,
Maik Roeder, Marco Bubke, Martin P. Holland, Neal Becker, Pete Ware, Peter
Torstensen, Reiner Wichert, Richard Jones, Steve Noble, Toby Sargeant and Gerrit
Sere.
Finally, many people have read the drafts and helped me write a better book by
sending me their comments - sometimes very long and detailed: Andre Gosselin,
Andy Anderson, Brent Burley, Christopher Farly, Damon Lynch, Dave Turner,
Dincer Aydin, Mark Summerfield, Robert Hicks, Sean Ahern and Yigal Duppen.
28
Chapter 1. Introduction
Developing decent software is difficult — monstrously difficult, in fact. People are
always looking for miracle cures, silver bullets that will help them creating great
software in no time with no conscious effort. In fact, almost everyone will agree to
the existence of a ‘software crisis’. Projects do deliver too little functionality, too
late and often of a too low quality. Frederick Brooks was the first to note this, in his
famous book The Mythical Man-Month. More’s the pity that there aren’t any
miraculous solutions for the many problems that plague software development.
There is simply no single innovation that will make you ten times more productive,
no single innovation that will ensure that whatever you do, you will produce
bug-free software and no single innovation that will make your applications run will
all the vim and vigor your users desire and deserve.
However, it is quite possible, by simply using the best possible tools and practices,
to be far more productive than would be possible by following the usual practices
and by using inferior tools.
It’s amazing how many software development environments have been designed
with something else than developer productivity as the main goal. There’s Visual
Basic, which, while infinitely more productive than previous attempts at creating a
rapid development environment for Windows, still is mainly concerned with
preventing people from creating applications that can compete with Microsofts’
own applications. Java, while quite usable, tries far too hard to protect me from
myself and my colleagues — like early versions of Pascal. C++ is enormously large
and complicated, because of its compatibility goals with C — almost too big to
learn to handle. In contrast, Python was designed to be small, practical and to be as
open as possible to the developer.
In Python, all other considerations, are secondary to considerations of development
speed, code maintainability and code reusability.
Python offers everything you need to put the best practices into practice, like object
oriented design, unit testing and maintaining documentation in the code, but it
doesn’t keep you from messing with the more messy parts of the operating system
— you can always use an extension module written in C or C++ — or with the
internals of Python itself. It is ideal for rapid prototyping, but also for the
development of large applications by large teams of programmers.
29
Chapter 1. Introduction
Python code is meant to be readable. Indenting correctly and neatly is not merely a
good habit: it is essential to delimit blocks of code. Likewise, there is little use for
comic-book swearing characters like ‘!@#$#%$’ that other languages use to
indicate the type of a variable, or even for variable declarations and all those other
things that keep you from writing the logic of your application. The most famous
description of Python is that it’s ‘executable pseudo-code’!
However, what Python has been lacking until recently was a good development
environment. Of course, since all Python code is simple text, and since you don’t
need pre-processors or compilers, you can get by with nothing more than a text
editor, like XEmacs Nedit, or MultiEdit. Indeed, I’ve used Nedit exclusively for
years — but some project management facilities, a tighter integration with a GUI
builder and a good debugger can make life infinitely more pleasant, and thus
productive.
BlackAdder is such an environment. Others are Wing IDE, PythonWorks,
PythonWin, Komodo and, perhaps, IDLE. Of these, only BlackAdder runs on both
Windows and Linux, includes a full-featured GUI designer and provides a
dependable debugger. Applications developed with Python and BlackAdder can run
on any Unix platform with X11 and on any 32-bits Windows platform (and in the
near future on Apple’s OS X, too).
1.1. Python
Python is a modern programming language, with strong object-oriented features, a
small set of basic functions and large set of libraries. The most important features of
Python are:
30
Chapter 1. Introduction
#!/usr/bin/env python ➊
#
# bootstrap.py
#
import sys ➋
from myapp import SomeClass ➌
def main(args): ➍
class=SomeClass(args)
class.exec_loop()
if __name__=="__main__": ➎
main(sys.argv)
31
Chapter 1. Introduction
➊ The so-called ‘hash-bang’ trick is useful on Unix systems only. If the first line
of any text file starts with #!, then the system will try to execute the application
that follows the #! with the rest of the file as input. In this case, the env utility
starts python, which runs the rest of the script.
➋ The standard Python module sys handles tasks like passing on command-line
arguments and lots of other things. Here we import the module, so we can pass
the command-line arguments to the application.
➌ All application code is in separate modules; the first of these we import here.
➍ This is the definition of the main function. By encapsulating this code in a
function, it won’t get run if this file were imported from another file.
➎ In this line, we check if this is a top-level script, instead of a file imported from
another file. This is done by looking at the variable __name__. If this is the
toplevel file, then the main(args) is run.
Python is, like Java, a language that is compiled to bytecode. Python uses a virtual
machine to run the bytecode. This virtual machine is written in C and interprets
each byte-code instruction, translates it to real machine code and then runs it. The
Python virtual machine differs from the Java virtual machine in that the byte-code
instructions are a bit more high-level, and that there are no JIT-compilers that
pre-compile chunks of byte-code to native machine code.
The translation from Python code to byte-code only happens once: Python saves a
compiled version of your code in another file with the extension .pyc, or an
optimized compiled version of your code that removes assert statements and
line-number tracking in a file with the extension .pyo.
However, that is only done with Python files that are imported from other files: the
bootstrap script will be compiled to bytecode every time you run it, but python will
create a myapp.pyc from a file myapp.py (which is not shown here).
Interpreted languages, even byte-code interpreted languages, have a reputation for
sluggishness. On the other hand, modern computers have a well-deserved reputation
32
Chapter 1. Introduction
for excessive processing power. The combination means that an application written
in a interpreted language can be fast enough for almost any needs.
Certainly, anyone who has ever tried to use a full-scale Java GUI application will
know the exact meaning of the expression ‘slow as frozen treacle’. There are several
reasons for the abominable slowness of Java applications, the most important of
which is the fact that all Java Swing gui elements are also written in Java. Every
pixel is put on screen by Java. Python, on the other hand, makes clever use of
available GUI libraries that are coded in C or C++ and thus run as native machine
code.
The ease with which Python can make use of native libraries is one of its strong
points. Thanks to this extensibility, you can write the logic of your application in
Python, and later rewrite the bottlenecks in C or C++. But even without writing
extension libraries, I have never encountered any problem with the performance of a
Python application.
33
Chapter 1. Introduction
Tkinter Yes Yes Yes, Tkinter is the most ancient Python GUI
mostly toolkit. It is based on tcl/tk, and has
neither the real platform UI look and feel,
nor a real Python programming style. A
good resource is John Grayson’s book,
Python and Tkinter programming.
PyQt Yes Yes OS X PyQt is based on Qt, the cross-platform
only GUI toolkit by Troll Tech. It’s also, not so
coincidentally, the subject of this book.
wxPython Yes Yes No wxPython is based on the wxWindows
toolkit. wxWindows is a crossplatform
wrapper around a native toolkit of each
platform: the standard Win32 controls on
Windows and GTK on Unix/X11.
FxPy Yes Yes No One of the smaller - in terms of user base
- toolkits, it is based on the FOX toolkit.
FxPy’s main feature is execution speed.
PyGTK Yes (a bit)Yes (If you PyGTK is based on GTK (formerly
(+PyG- run a known as the Gimp Toolkit). Not really
nome) separate intended for cross-platform work, it has
X Server recently been ported (more or less) to
on OS X) Windows.
Python- Yes No No Pythonwin is the - rather
win underdocumented - binding to Microsofts
MFC library. It’s not portable, of course.
There are many others GUI toolkits available, both dead and alive. For a complete
listing, please see Cameron Laird’s notes on Python GUI’s at:
http://starbase.neosoft.com/~claird/comp.lang.python/python_GUI.html. However,
the really serious options for someone selecting a toolkit are Tkinter, PyQt and
wxPython. I have selected PyQt for my own use, based on criteria of performance,
34
Chapter 1. Introduction
35
Chapter 1. Introduction
There is also a simple but dependable debugger, a Python interpreter window for
when you want to make a quick test, and last, but not least, an excellent gui designer.
Especially the gui designer is worthy of serious attention. It is based on Qt
Designer, which is a standard part of the Qt library. It produces designs that can, at
your choice, be transformed into executable Python code or compilable C++ code.
This means that if you prototype your application in BlackAdder and later, for
whatever reason, decide to move it to C++, you can keep all the interface work
you’ve done already.
Using Python and PyQt does not force you to use BlackAdder: you can, if you live
in the Unix world, use the free, GPL, version of Qt, which includes the original Qt
Designer, the free version of PyQt and Python, to create the same applications. On
Windows or OS X, you can use the non-commercial version of Qt with the free
PyQt binaries - these cannot be used to develop commercial applications, or in a
in-house commercial setting, but are completely identical to the Unix/X11 GPL
library in all other respects.
The GUI design files Qt Designer produces and those of BlackAdder are completely
compatible. Likewise, using BlackAdder doesn’t force you to use PyQt - you can
just as well create a Tkinter application with BlackAdder. You won’t find much use
for the Designer module though, since that only knows about the Qt widgets.
All in all, BlackAdder combines all the tools you need to develop good GUI apps in
an extremely convenient package, and the added productivity of this system is well
worth the small expense, especially if you intend to develop commercial
applications on Windows.
36
I. Introduction to the
BlackAdder IDE
Table of Contents
2. Installation ..........................................................................................................39
3. Interface ..............................................................................................................47
4. Introduction to Python ......................................................................................57
5. Debugging ...........................................................................................................73
There are several possibilities for starting out with Python and PyQt. You can buy
BlackAdder, the PyQt IDE, or you can download the freely available components
— Python, Qt and PyQt and use your own tools to write your application.
In this part I’ll first guide you through the installation of BlackAdder or PyQt. Then
we make a brief tour of the interface of BlackAdder. A very short introduction to
Python and the first concepts of programming follows, and we conclude with a
chapter on using the BlackAdder debugger.
Chapter 2. Installation
In this chapter I briefly describe how to install BlackAdder on Windows and Linux.
After that, compiling PyQt from source is described in a little more detail.
Of course, a book generally has a longer life than a certain version of a software
package, so installation details might have changed between time of writing and
time of buying—so don’t forget to read the README files!
2.1.1. Windows
To install BlackAdder on Windows you need the following components:
• Python. (Be careful to choose the version of Python that is right for your version
of BlackAdder.)
• BlackAdder.
• The BlackAdder Qt module.
•
And eventually, the Egenix MX ODBC module, if you want to do database work.
Now it’s simply a matter of installing the components, one after another. Every
component is provided in a comfortable Windows installer package.
39
Chapter 2. Installation
Installing BlackAdder
BlackAdder will now be ready to run — a friendly icon has appeared on your
desktop, just begging to be clicked.
2.1.2. Linux
There are rpm packages for a lot of distributions: Mandrake, RedHat and SuSE.
Additionally, there is a .tgz package for Slackware.
Installing BlackAdder does not differ from installing any other package for your
favorite distribution — you can use a fancy gui like KPackage, or type
on the command line, if you’re installing the 3.1 beta for SuSE Linux. The actual
name of the rpm will vary, of course.
40
Chapter 2. Installation
Additionally, you might want to set two environment variables in your .bashrc
file. Installing BlackAdder and Python in the default location isn’t necessary, but if
you deviate from the standard BlackAdder installation directory, you need to set the
following variables.
Now, simply typing "ba" on the command line will start BlackAdder.
41
Chapter 2. Installation
BlackAdder
All components that combine to form a PyQt development environment are also
freely available. Python, Qt, Qt Designer, sip, PyQt and editors are all available as
open source. If you use Linux—and particularly if you use a modern and complete
distribution like SuSE or Redhat—everything you need is included on your
distribution media, including PyQt. There are also Debian packages of PyQt
available. Installing these ready-made packages is very easy, but they are not always
completely up-to-date. In the next section, I will discuss building PyQt from source,
which is necessary if you want to always run the latest version of PyQt.
Windows users who want to use PyQt without BlackAdder have some downloading
to do, but all components are available as binary packages that come with easy to
use Windows installers.
Installing PyQt from source on Windows falls outside the scope of this book, partly
because it is quite complicated, and partly because I don’t have a C++ compiler for
Windows. The Qt library essentially demands Visual C++.
You can also access the PyQt CVS repository (the central place where the most
current code is kept — also at http://www.thekompany.com). Compiling PyQt from
CVS source entails creating the C++ bindings code from the sip definition files, and
then carrying on as if you had downloaded the source. Keep in mind that CVS
versions of software are not expected to work!
• sip
• PyQt
• Eventually: PyKDE
Be careful to choose versions of packages that fit each other. You can compile PyQt
with most versions of Qt, but Python 2.1 will give better results than Python 2.0,
and so on.
42
Chapter 2. Installation
You need to compile and install sip before compiling PyQt. After unpacking the sip
tar archive, you will need to give the following commands:
If your Python or Qt installation is in an odd place, then chances are that the
configure script cannot find it. In that case, you should give their locations on the
command line:
This will build the sip library and executable, and install them (most likely in
/usr/local/). With this done, it is time to do the same with PyQt. This time, the
make command will take a long time to run, because PyQt is a very large set of
bindings, and the GNU C++ compiler isn’t the fastest around.
The whole process might take a while, but should not pose any problem.
Sometimes, however, things go wrong...
43
Chapter 2. Installation
If you are experiencing problems, you probably have several versions of Python or
Qt on your system, and the compilation configuration process inevitably picks the
wrong one — for instance Qt 2.3.1 for sip and then Qt 3.0.0 for PyQt. Murphy’s law
cannot be avoided! This hurts compilation — but is easily avoided by giving the
right versions at the ./configure command line.
If you have determined that this is not the problem, your best bet will be to
subscribe to the PyQt mailinglist: http://mats.gmd.de/mailman/listinfo/pykde,
where most of us have found succor more than once.
2.2.2. Windows
You can develop applications on Windows systems with PyQt using only gratis
software. Life will certainly be more difficult than if you buy BlackAdder, because
you miss the nice integration of editor, debugger and operating system. Another
issue is licensing: if you buy the professional edition of BlackAdder, you can write
commercial software. If you use the non-commercial version of the Qt library and
the separately available packages of sip and PyQt, you are not allowed to sell your
programs: you are not even allowed to use your software yourself in a commercial
setting. However, if you want to develop PyQt on windows without spending any
money, you need the following components:
44
Chapter 2. Installation
SciTE, which uses the same editor component as BlackAdder, is very powerful and
pleasant to use. Get SciTE from http://www.scintilla.org/SciTE.html. (SciTE is also
available for Linux.)
You job is then reduced to manually installing Python, Qt, PyQt, and an editor.
Then you can get started on developing your application.
45
Chapter 2. Installation
46
Chapter 3. Interface
In this chapter we quickly walk through the various components of the BlackAdder
IDE. Once you have BlackAdder installed, you can start it by typing ba at the Unix
shell prompt, or double-clicking the new icon on your desktop. You’ll be greeted by
a stylish splash screen, followed by the BlackAdder application window.
Note: Please keep in mind that this chapter was written using the beta version
of BlackAdder. As a result, certain aspects of BlackAdder were not yet in their
final form. For instance, the toolbar icons are expected to change.
If, on the other hand, you are confronted by a window telling you that the Python
interpreter has died, you will probably need to correctly set the path to the Python
47
Chapter 3. Interface
However, if all is well, you can start exploring your new development environment.
3.1. Menubar
The BlackAdder menubar combines functionality for the editing of Python source
code and the creation of GUI forms.
The Tools, Layout and Preview menus contain commands for the creation of
forms, while Run is used to start and debug Python scripts. File and Edit have
commands for both tasks.
You can hide or unhide various important parts of BlackAdder with options from
the Window menu. These are the project Explorer, the Property Editor, the Object
Hierarchy window, the Traceback viewer and the Python interpreter window.
3.2. Toolbars
BlackAdder possesses an imposing array of toolbars. I’d certainly advise you to not
emulate this example in your own application!
48
Chapter 3. Interface
Most of the toolbars are used when designing forms, as they represent different
widgets and layout strategies. These widget buttons really belong in a floating tool
palette, but let’s gloss over that user interface design nicety.
Going from left to right and top to bottom on the previous image, we encounter the
following toolbars:
49
Chapter 3. Interface
3.2.5. Widgets
Next follows a set of buttons that insert display widgets in your design: a textlabel, a
picture label, and LCD number, a line, a progressbar, and finally, a textview and a
more complex textbrowser (this is a small html browser in itself). These last two
buttons are used to insert rich text widgets.
3.2.6. Help
The lonely button on the last toolbar of the second row gives you help if you first
click on the button, and then on the object you want help with. By clicking it and
then subsequently clicking on all toolbar buttons, you’ll discover that I haven’t been
lying to you in this section.
50
Another random document with
no related content on Scribd:
Las que eran madres tomaban en sus brazos a mis hijos, como para
admirarlos, separándolos de su padre, y los pasaban de mano en
mano. Después de gratos coloquios, ¿cómo lo creerás?, sacan puñales
que llevaban ocultos bajo sus vestidos, y las unas matan a mis hijos, y
las otras, como si fuesen mis enemigas, sujetan mis pies y mis manos
y cuando quería socorrerlos y levantar mi cabeza, me retenían por los
cabellos; si movía las manos, nada conseguía contra tantas mujeres. A
fin, añadiendo un daño a otro, perpetraron un crimen espantoso: con
sus broches[78] hirieron las niñas de mis ojos y las llenaron de sangre
después huyeron de la tienda. Yo salté entonces como una fiera que
persigue a sanguinarios perros, tentando la pared como un cazador, y
rompiendo y destrozándolo todo. Esto he sufrido, ¡oh Agamenón!, po
hacerte bien y matar a tu enemigo. Para no pronunciar más largo
discurso, resumiré en pocas palabras cuanto mal se ha dicho antes de
las mujeres, cuanto ahora se diga y se dirá después: ni la tierra ni los
mares albergan ningún ser que pueda comparárseles, lo cual, en
verdad, saben como yo los que las tratan.[79]
EL CORO
¡Ay de mí! Vencido, a lo que parece, por una esclava, hasta los
seres más despreciables me castigarán.
HÉCUBA
¿Y por qué no, habiendo cometido tantos delitos?
POLIMÉSTOR
ARGUMENTO
La diosa Afrodita, despreciada por Hipólito, hijo de Teseo, deseoso
de conservar su virginidad, trama su ruina y la satisfacción de su
venganza, inspirando a su madrastra Fedra un amor violento por él
pero no osando declarárselo, y víctima de su pasión vehemente, la
confía a su nodriza en ausencia de su esposo Teseo, la cual comete la
insigne imprudencia de participarla a Hipólito, que se indigna y la
rechaza con toda su energía. La desdichada Fedra, sabedora del ma
éxito de esta tentativa, resuelve suicidarse y ejecuta su proyecto
ahorcándose, si bien se venga de su hijastro dejando al morir unas
tablitas suspendidas de su cadáver, en las cuales dice que, contra su
voluntad y forzada por Hipólito, ha manchado el lecho nupcial
Entonces Teseo, sin informarse con escrupulosidad de la certeza de
esta acusación, y recordando que Poseidón le había prometido realiza
tres votos suyos, le pide que mate a Hipólito, y lo destierra de su reino
El mísero e inocente joven, lleno de dolor, y no queriendo faltar a su
juramento de no publicar la declaración de la nodriza, huye en su
carro, acompañado de sus más fieles servidores, y perece en el camino
acometido por un toro, que suscita contra él el dios marino. Cuando lo
traen moribundo a la presencia de Teseo, se aparece Artemisa, su
amiga y protectora, descubre su inocencia y lo consuela, profetizando
los honores y fiestas que se le tributarán en lo sucesivo.
Esta tragedia, imitada por Séneca y por Racine, no puede juzgarse
desde el punto de vista de nuestras ideas como lo han hecho de
ordinario la mayor parte de los críticos. Han olvidado que este
espectáculo era entre los griegos esencialmente religioso, dirigido a
poner de relieve el incontrastable poder del destino y la debilidad
humana, fortificando por el temor dicho sentimiento religioso, y que e
Hipólito no solo no produce ese efecto, puesto que nos inspira odio y
aversión justísima contra Afrodita, diosa vengativa y egoísta, sino que
la base de su argumento es un amor adúltero e incestuoso, asunto
mirado como indigno de la solemnidad y elevación de la tragedia, que
suscitó con razón en su tiempo las censuras más acerbas. Por lo
demás, no estamos, conformes con los que juzgan las obras dramáticas
griegas como podrían juzgar una tragedia moderna.[82] Hipólito no es
un caballero andante de la Edad Media, sino un griego de los tiempos
heroicos, excesivamente casto, que miraba a las mujeres con
desprecio, y que justamente indignado de la declaración de la nodriza
de Fedra, huye de ella y ni siquiera repara en el coro de mujeres que lo
observa. Por consiguiente, no hay en su conducta la inverosimilitud y la
grosería que se supone, sino, al contrario, un motivo más para que
Fedra, a quien no ve, llena de vergüenza, precipite su resolución de
suicidarse. Verdad es que su larga declamación contra las mujeres no
es del mejor gusto; pero también convendremos en que pocas veces se
debería hablar de ellas como Hipólito lo hace esta bajo la impresión de
las infames proposiciones de la nodriza y del descubrimiento del amo
criminal de la mujer de su padre. Si Teseo no aparece hasta el fin, no
es por otra razón que para hacer más verosímil cuanto sucede en su
ausencia y después de su llegada; solo así, y dejándose arrastrar de
dolor que siente al contemplar el cadáver de su esposa, se concibe
que, trastornado por la ira, condene a su hijo al destierro y pida a
Poseidón su muerte. La de Fedra y su póstuma venganza son tan
naturales y verosímiles, que lo contrario sería indudablemente afectado
e inverosímil. ¿Fedra era cristiana o era griega? Suicidándose dominada
por el amor, el despecho y la vergüenza, ¿qué cosa más natural que su
venganza de Hipólito? Los héroes y heroínas de la Grecia, como el Áyax
de Sófocles, no se arrepientan de su propósito, una vez decididos a
ejecutarlo como debieran hacerlo si fueran buenos cristianos. Lo mismo
acontece con las demás críticas superficiales que se han hecho de esta
tragedia, que no refutamos tan fácilmente como las anteriores para no
alargar más de lo justo estas líneas. En nuestro concepto, y
prescindiendo del defecto capital indicado, el Hipólito es una obra
dramática digna de la Grecia y de Eurípides, y hay en ella rasgos y
escenas, como la del diálogo entre la nodriza y Fedra, en que esta le
revela su pasión, que no ceden a las mejores de ninguna otra de
cualquier época ni de cualquier pueblo.
Respecto a la fecha de su representación, no tenemos otros datos
que los que nos ofrece el autor del argumento griego: sus palabras son
las siguientes: ἐδιδάχθη ἐπὶ ᾿Επαμείνονος ἄρχοντος Ὀλυμπιάδι πζ’ ἔτε
τετάρτῳ. πρῶτος Εὐριπίδης, δεύτερος ᾿Ιοφῶν, τρίτος Ἴων. ἔστι δὲ
οὗτος ὁ Ἱππόλυτος δεύτερος, καὶ Στεφανίας προσαγορευόμενος
ἐμφαίνεται δὲ ὕστερος γεγραμμένος· τὸ γὰρ ἀπρεπὲς καὶ κατηγορίας
ἄξιον ἐν τούτῳ διώρθωται τὸ δράματι.
Como al mismo tiempo los últimos versos de esta tragedia hablan de
la muerte de los grandes hombres, se ha creído que Eurípides alude a
la de Pericles, ocurrida en el año II de la guerra del Peloponeso, cuya
fecha concuerda, en efecto, con la indicada por el autor citado: esto es
en la olimpiada 87, 4. Sépase, además, que esta tragedia, llamada
Hipólito que trae la corona (στεφανηφόρος), es una refundición de
otra, cuyo título era Hipólito velado (καλυπτόμενος), porque no se
contentaba con ofrecer la corona a Artemisa, volviendo las espaldas a
Afrodita, sino que se cubría el rostro al pasar por delante de la estatua
de esta.
PERSONAJES
Afrodita.
Hipólito, hijo de Teseo y de la amazona Antíope.
Servidores de Hipólito.
Coro de mujeres trecenias.
La nodriza de Fedra.
Fedra, esposa de Teseo, hija de Minos.
Un mensajero.
Teseo, rey de Atenas, hijo de Egeo.
Otro mensajero.
Artemisa.
La acción es en Trecén.
La escena representa el palacio de Teseo en esta ciudad, y a la izquierda y a la derecha de la
puerta se ven las estatuas de Afrodita y de Artemisa.
AFRODITA
Sí, porque los hombres, obrando así, obedecen las leyes divinas.[95]
SERVIDOR
¿Y por qué tú no saludas a una diosa veneranda?
HIPÓLITO
¡Oh males humanos y tristes dolencias! ¿Qué haré por ti? ¿Qué no
haré? Mira la clara luz que te alumbra, mira el aire. Fuera del palacio
está ya el lecho en que descansas de tus dolores. Solo hablabas de
venir aquí; pero no tardarás en volver a tu nupcial aposento. Pronto
varías de parecer, y nada te divierte; no te agrada lo que posees, y
anhelas lo que no tienes. (Dirigiéndose al público mientras Fedra
dormita). Más fácil es enfermar que asistir al doliente, porque lo
primero es sencillo y natural, y en lo segundo se junta la aflicción de
alma al sufrimiento del cuerpo. Llena de tormentos está la vida
humana, y no hay descanso en nuestras penalidades; y si tan dulce es
vivir, a lo mejor nos envuelven las tinieblas de la muerte. Perdidamente
nos enamoramos de esta luz, que brilla alguna vez en la tierra, sin
saber lo que pasa en la otra vida, ni conocer nada de lo que sucede
debajo de nosotros; temerarias son las ilusiones que nos arrastran.
FEDRA (revolviéndose inquieta).
¡Ay, ay! ¡Ojalá que yo beba agua cristalina de fresca fuente, y que
bajo blancos álamos y en verde prado yazga reclinada!
LA NODRIZA
¡Ay de mí!
LA NODRIZA
Qué, ¿te interesa esto?
FEDRA
Tú lo dices, no yo.
LA NODRIZA
No pases más adelante, no, que está bien lo que dices, aunque
¡por los dioses!, sea vergonzoso; porque si hasta ahora, a pesar de m
amor, no he faltado, si con palabras especiosas me inspiras
sentimientos indignos de mí, pereceré deslizándome en el abismo de
que huyo.
LA NODRIZA
Si tal te parece, no debiste darle entrada en tu pecho; pero como
sucede lo contrario, obedéceme, que también redundará en tu
beneficio. Yo tengo en casa filtros[113] que aplacan la fuerza del amor, y
ahora me he acordado de ellos, y sin vergüenza ni menoscabo de tu
razón te librarán de ese mal si no eres débil; pero necesitamos alguna
prenda del que amas, algún rizo o pedazo de su vestido, para que sea
una misma vuestra amorosa pasión.
FEDRA
Estrofa 1.ª — Amor, Amor que con la mirada inspiras los deseos e
infundes suave deleite en los ánimos de aquellos a quienes haces la
guerra: que nunca te vea con daño mío ni tiránico me domines. Ni e
fuego ni los rayos que despiden los astros pueden compararse a la
saeta que lanza Amor, hijo de Zeus.
Antístrofa 1.ª — En vano, en vano junto al Alfeo[115] y en el templo
pítico de Febo acumula hecatombes la Grecia; no adoramos al Amor
tirano de los corazones, que guarda la llave de los lechos más
codiciados y nos pierde y nos infecta cuando nos acomete
enviándonos todo linaje de males.
Estrofa 2.ª — Pues Afrodita dio al hijo de Alcmena la doncella de
Ecalia,[116] que no había conocido el himeneo, y que por tanto ignoraba
lo que era un esposo y un tálamo nupcial, llevándola desde su palacio
en rápida nave, cual ministro veloz del Orco, con sangre y fuego, y
celebrando terribles bodas. ¡Cuán desventuradas fueron sus nupcias!
Antístrofa 2.ª — ¡Oh santas murallas de Tebas! ¡Oh fuente Dircea
Vosotras fuisteis testigos del poder de Afrodita. Con ardiente rayo
aletargó a la madre de Dioniso, engendrado por Zeus, unida a él en
himeneo funesto. Abrasa lo que toca con su hálito, y vuela como una
abeja.
FEDRA
Callad, mujeres; somos perdidas.
EL CORO
¿Qué significan tus quejas? ¿Qué tus voces? Di, ¡oh mujer!, ¿qué
súbito rumor te atorra?
FEDRA
¡Oh tierra, nuestra madre, oh inmensa luz del sol! ¿Qué palabras
nefandas han manchado mis oídos?
LA NODRIZA
Calla, hijo, no te oiga alguien.
HIPÓLITO
¡Oh Zeus! ¿Por qué dispusiste que las mujeres viesen la luz del sol
si son cebo engañoso para los hombres? Si deseabas que estos se
multiplicasen, no debías haberlas creado, sino que ellos en sus
templos, pesando el oro, o el hierro, o el bronce, comprasen los hijos
que necesitaran, pagando el justo precio de cada uno, y que viviesen
en sus casas, libres de femenil compañía. Ahora, como han de mora
con nosotros, agotan nuestros recursos. Manifiesto es de aquí qué
azote tan grande es la mujer; pues el padre, que la engendra y la
educa, da además la dote y la casa para librarse de ella: al contrario, e
que recibe en su hogar esta peste destructora, goza engalanando a
una pésima estatua, y la viste con sus mejores ropas, y e
desventurado gasta así sus rentas. Obligado se ve, si ha de
emparentar con familia ilustre, a mostrarse alegre y ser fiel en su
amargo consorcio, o si es buena la esposa y pobres los suegros, a
remediar bondadosamente su infortunio. Lο mejor, si ha de vivir con
nosotros, es que la fortuna nos favorezca, dándonos una compañera
inepta y demasiado sencilla. Aborrezco a la sabia; que no albergue un
mismo lecho a la que sepa más que yo, y más de lo que conviene a
una mujer. Porque Afrodita hace a las doctas las más depravadas, y la
sencilla, por sus cortos alcances, está libre de deshonestidad
Convendría también que no las acompañasen esclavas, sino que
habitasen con ellas monstruos mudos o fieras, con quienes no
pudiesen hablar ni oír su voz. Ahora sus esclavas no cesan de urdi
intrigas vituperables, y después las ejecutan fuera de su casa, como tú
(A la nodriza), ¡oh malvada!, osando proponerme que profane e
sagrado lecho de mi padre: yo me purificaré de esta mancha en agua
corriente, lavando con ella mis oídos. ¿Qué me sucedería si fuese
criminal, cuando ni aun me creo puro habiéndola oído? Ten muy
presente lo que te digo, ¡oh mujer!; solo mi piedad te salva; a no
haberme tendido una red con mi propio juramento, jamás me
contuviera, y lo hubiese revelado a mi padre. Pero ya que Teseo está
ausente por mucho tiempo, me iré de este palacio, y mis labios
guardarán silencio. Veremos a ver cuando vuelva cómo arrostráis su
presencia tú y tu señora: ya avisado, sabré hasta dónde llega tu
audacia. ¡Que perezcáis ambas! Nunca me cansaré de odiar a las
mujeres, aunque alguno diga que tal es siempre mi propósito; y no se
engaña, en efecto, porque son siempre malvadas. Que aprendan a se
castas, o nunca dejaré de ensañarme con ellas.[120] (Retírase).
FEDRA