Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (4 votes)
31 views

GUI Programming With Python QT Edition Boudewijn Rempt Download PDF

ebook

Uploaded by

jeimondabi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
31 views

GUI Programming With Python QT Edition Boudewijn Rempt Download PDF

ebook

Uploaded by

jeimondabi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

Full download ebook at ebookname.

com

GUI Programming with Python QT Edition Boudewijn


Rempt

https://ebookname.com/product/gui-programming-with-python-
qt-edition-boudewijn-rempt/

OR CLICK BUTTON

DOWLOAD NOW

Download more ebook from https://ebookname.com


More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Rapid GUI Programming with Python and Qt 1st Edition


Mark Summerfield

https://ebookname.com/product/rapid-gui-programming-with-python-
and-qt-1st-edition-mark-summerfield/

Programming ArcGIS with Python Cookbook 2nd Edition


Eric Pimpler

https://ebookname.com/product/programming-arcgis-with-python-
cookbook-2nd-edition-eric-pimpler/

Game Programming With Python Game Development Series


1st Edition Riley

https://ebookname.com/product/game-programming-with-python-game-
development-series-1st-edition-riley/

Programming Python 4th Edition Mark Lutz

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/

Programming Computer Vision with Python Tools and


algorithms for analyzing images 1st Edition Jan Erik
Solem

https://ebookname.com/product/programming-computer-vision-with-
python-tools-and-algorithms-for-analyzing-images-1st-edition-jan-
erik-solem/

Programming in Python 3 A Complete Introduction to the


Python Language 2nd Edition Summerfield

https://ebookname.com/product/programming-in-python-3-a-complete-
introduction-to-the-python-language-2nd-edition-summerfield/

Python Interviews Discussions with Python Experts 1st


Edition Mike Driscoll

https://ebookname.com/product/python-interviews-discussions-with-
python-experts-1st-edition-mike-driscoll/

Python Programming for the Absolute Beginner 3rd


Edition Michael Dawson

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

GUI Programming with Python: QT Edition Edition


Published July 2001
Copyright © 2001 by Commandprompt, Inc

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

hide the complexity that is a part of any programming effort.


Both are right, of course, so I decided to give you both small examples and one
really large one. Part I and II of this book concern themselves with concepts: here
the examples are small, often amounting to less than one page of code. Part III takes
you through the development of a complete, complex application. In this case an
editor, but one with a lot of extra features. I think it’s a very good way of learning
what developing complex applications entails - I spare you none of the nasty details
that software development entails.
I have tried to keep to a very clear style of coding, with few or none of the clever
hacks that are possible in Python — like adding the methods of one class to another,
or creating lists of function objects. The purpose is to tell you about writing real
applications using Python and Qt. Clever hacking has its place, but is best savored
on its own.
The emphasis of the book is also firmly on application development, not on creating
graphics per se — although several techniques are mentioned here and there that
have to do with creating charts and graphs.

1. Who is using PyQt


The combination of Python and Qt is extremely powerful, and is used in a wide
variety of applications. People are scripting OpenGL applications with it, creating
complex 3D models, animation applications, writing database applications, games,
utilities and hardware monitoring applications. It is used in open source projects,
but also by large companies, like Disney Television and Media. If you’re not
working on embedded software, hardware drivers or a new operating system,
chances are that PyQt is the right choice for you, too.

2. For whom is this book intended


This is the first book on Python and Qt. There have been quite a few books on C++
and Qt, but you would need to be fairly adept at mentally searching and replacing
C++ language constructs to be able to use those books for pleasure and profit if

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.

3. How to read this book


Like ancient Gaul, this book is divided in three parts. The first part details the
installation of PyQt and of BlackAdder. Then the book takes you through a tour of
the interface of BlackAdder. You might want to read this part in order. There is also

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:

boudewijn@maldar:~/doc/pyqt/ch3 > python sigslot.py


Object with ID 135113236 Got signal: message
Object with ID 135115668 Got signal: message
Object with ID 135318532 Got signal: message
boudewijn@maldar:~/doc/pyqt/ch3 >

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:

• Compiled to byte-code, interpreted by a virtual machine.


• High-level data structures: lists, tuples and dictionaries
• Dynamic: you can even add new base-classes to an existing object, run-time.
• Portable: the same Python bytecode will run — depending on which version of
Python you use and which C or C++ extensions are used — on Unix, Windows,
MacOS, Amiga, Palm OS and many others.

30
Chapter 1. Introduction

• Extensible with modules written in C or C++: there is no performance penalty for


calling native code, as there is when calling native code from Java.
• An object-oriented programming model, but also supports functional
programming (a bit) and old-fashioned structured programming.
• Enormous set of extension libraries: for database access, high-performance
number-crunching, for sound-file analysis, for GUI programming and countless
other tasks.
• Built-in regular expression engine that works on both regular and Unicode
strings.
• Use of indentation instead of braces begin/end pairs to delimit blocks of code.
This practically forces readable code.
Your Python code resides in files, ending with .py suffix. These files can be
grouped in modules, in the form of directories with an indexfile called
__init__.py, and you can import elements from modules and files in other files.
There is one file you use to start your application. It will usually simply import the
necessary modules and start the application explicitly in a main (args) function.
Maybe the introduction is bit early to start with actual code examples, but let’s have
an example of a Python bootstrap script anyway:

Example 1-1. Bootstrapping a Python application

#!/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.

1.2. GUI programming with Python


One area where you do want the snappiest response possible is your user interface.
Users are notoriously impatient creatures, and they are right. Responsiveness is
important. Likewise, conformance to platform standards is important, as is a well
thought-out programming model, to make your life easier. You want to have as little
GUI code to as possible, because that means that there are less opportunities for
bugs. With these criteria, we can set out to select a good GUI toolkit.
That it is possible at all to select a GUI toolkit might come as a bit of a surprise to
Visual Basic developers, who cannot choose, but have to use whatever Microsoft
provides. There is a cornucopia of GUI toolkits available for Unix/X11. Because
Python is so easily extensible with C and C++ modules, a large part of them is
usable, ‘bound to’ is the technical term, from Python. Quite a few of those toolkits
are available on Windows too. Because all computer intensive drawing and
interaction code runs in native machine code, outside the Python virtual machine,
the interface can be as responsive as the interface of an application written in C or
C++.
The following GUI toolkits exist for Python:

33
Chapter 1. Introduction

Table 1-1. GUI Toolkits for Python

Gui Win- MacOS Notes


Toolkit dows Unix/X11

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

programming model, completeness of the assortment of widgets and ease of


installation. Oh, and because it was the most fun to use, of course!
There were other considerations, of course. Tkinter is often very slow - try running
the IDLE IDE that comes with Python. In contrast, PyQt is very snappy. The Tcl-tk
programming model that Tkinter is based on doesn’t translate as well to Python as
the modified C++ programming model of PyQt. PyQt has also been very well
designed: I just love the signal/slot mechanism of PyQt. There is also just about
every type of widget I need, and PyQt is easy to install. WxPython, because it’s a
library (wxPython) based on a library (wxWindows) based on a library (MFC or
GTK) can be really difficult to get up and running. Finally, the GUI designer in
BlackAdder (or the free equivalent Qt Designer) is a strong point in favor of Qt, too.
The most important features of PyQt are:

• Based on Trolltechs C++ Qt toolkit.


• Runs on Windows and Unix/X11 (and soon on Apple’s OS X)
• Uses the innovative signals/slots paradigm to couple GUI items and actions.
• Binds almost the complete Qt library
• Allows subclassing of Qt classes in Python
• Allows applications to mimic the look and feel of Windows, Motif, CDE, SGI
and MacOS 9, or take on a custom look and feel.
• Comes with an enormous inventory of advanced GUI controls, such as a canvas,
an editable table module and a rich text editor (in version 3.0).

1.3. About the BlackAdder IDE


BlackAdder is growing into a rather nice development environment for Python and
PyQt applications. You can use it to rapidly prototype interfaces, or to develop
complete, complex applications in a very short time.
The central feature of BlackAdder is the editor, which is specially geared towards
working with Python, and includes folding, syntax highlighing and auto-indent.

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. Installing BlackAdder


PyQt can be used on Windows, Unix/X11 and soon OS X, but BlackAdder is only
available for Windows and Unix/X11 (due to licensing restrictions).

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

boud@calcifer:~/tmp > rpm --install BA-personal-1.0Beta3-


1_tkc_suse71.i386.rpm

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

KPackage with the BlackAdder rpm

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.

export BLACKADDERDIR=/usr/lib/BlackAdder export


BLACKADDERPYTHON=/usr/local/bin/python

Now, simply typing "ba" on the command line will start BlackAdder.

2.2. Installing sip and PyQt without

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!

2.2.1. Building from source on Linux


Assuming you already have an installation of Python and Qt, you first need to
gather the following packages if you want to build PyQt from source:

• 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:

boud@calcifer:~/src/sip-2.5 > ./configure; make

And, when building is complete, become superuser and type:

root@calcifer:/home/boud/src/sip-2.5 > make install

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:

boud@calcifer:~/src/sip-2.5 > ./configure \


--with-qt-dir=/opt/qt \ --with-
python=/usr/local/bin/python

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.

boud@calcifer:~/src/PyQt-2.5 > ./configure; make ...


boud@calcifer:~/src/PyQt-2.5 > su Password:
root@calcifer:/home/boud/src/PyQt-2.5 > make install

The whole process might take a while, but should not pose any problem.
Sometimes, however, things go wrong...

2.2.1.1. Problems with compilation


While not really difficult, compiling from source is an exercise to be attempted only
by the technically adept. Certain problems have cropped up throughout the life of
PyQt, only to be solved in later versions. Other problems have been caused by the
version of the GNU C++ compiler used in certain releases of Redhat: gcc 2.96.

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:

• The Non-commercial licensed Qt library from http://www.trolltech.com. This a


full version of Qt. You cannot build commercial applications with this library,
and you cannot use your software in a commercial setting. Additionally, you
must make the source to your software available. See
http://www.trolltech.com/products/download/freelicense/noncommercial-dl.html
for more information.
• You also need the precompiled PyQt for Windows library from
http://www.thekompany.com/projects/pykde/. This is made available under the
same license as the non-commercial version of Qt. You don’t need to download a
separate copy of sip.
• Of course, Python is needed, too! Get it from http://www.python.org.
You also need a nice editor to type your Python code with. notepad just won’t do -

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.)

The SciTE editor.

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.

BlackAdder and its ‘About’ dialog.

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

interpreter executable (either python or python.exe on Windows), as described in


Section 2.1.2.

Python has given the ghost.

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!

The BlackAdder collection of toolbars.

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:

3.2.1. File toolbar


This toolbar contains buttons that can be used to create, open and save BlackAdder
projects, single Python scripts and dialog designs. The last two buttons are used to
compile either the current dialog design, or all dialog designs in the current project.
In this case, compilation means that the XML-based designs are converted to usable
Python code. Running a project also means that all form designs will be compiled to
Python.

The file toolbar.

3.2.2. Edit toolbar


Undo, redo, cut, copy and paste are all fairly standard functions, and work on both
widgets in dialog design mode, and on text in the editor.

The edit toolbar.

3.2.3. Execution toolbar


This toolbar contains buttons to start scripts and projects, debug scripts and
projects, restart debugging, continue running while debugging, single stepping,
clear the breakpoints in the currently edited script, clear all breakpoints set in the
whole project, and cancel or stop debugging.

49
Chapter 3. Interface

The execution toolbar.

3.2.4. Layout manager toolbar


On the next row we find the layout manager toolbar. Again, from left to right, there
are buttons to resize widgets, insert a horizontal, vertical and grid layout manager,
remove the current layout manager and insert a spacer object (the spacer is the the
curious springy thing).

The layout toolbar.

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.

The first widget toolbar.

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.

The help toolbar.

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

No seas audaz ni insolente, ni hables así de todas las mujeres


excitado por tus males; muchas de nosotras somos objeto de envidia
aunque otras seamos malas en efecto.
HÉCUBA
La lengua de los hombres, ¡oh Agamenón!, nunca debía valer más
que sus hechos, sino solo hablar bien si bien obraban, y si sus acciones
eran vituperables, que sus palabras ahuyentasen a las gentes, y no
revestir sus injusticias con elocuentes frases. Sabios los hay, en
verdad, hablando con exactitud; pero es difícil serlo siempre, y cada
cual recibe su premio o su castigo, y ninguno lo ha evitado hasta
ahora. Y así es como debo empezar por lo que a ti atañe; pero ahora
toca a él, y será a su vez interrogado, ya que ha dicho que por ahorra
dos trabajos a los griegos, y por afecto a Agamenón, ha dado muerte a
mi hijo. Pero advierte en primer lugar, ¡oh infame!, que nunca fueron
los bárbaros amigos de los griegos, ni podrán serlo. ¿Qué esperabas
conseguir? ¿Intentabas acaso contraer algún matrimonio ventajoso, o
vengar a tus parientes? ¿Qué motivo te impulsaba? ¿Temías quizá que
volviendo los griegos con sus naves, destrozasen tus sembrados? ¿A
quién lo persuadirías? El oro y tu codicia, si quieres decir la verdad
han sido los asesinos de mi hijo. Pruébame, si no, por qué cuando
Troya era feliz, cercada de sus murallas, y Príamo vivía, y Hécto
empuñaba su robusta lanza, no lo mataste entonces por conciliarte la
gracia de este, y lo alimentabas y lo hospedabas en tu palacio. ¿Po
qué no lo entregaste vivo a los griegos? ¿Por qué cuando se nubló
nuestra fortuna y los enemigos llenaron de humo la ciudad, mataste a
tu huésped, al que se había refugiado en tu hogar? Oye además otras
razones que probarán tu delito. Si eras amigo de los griegos, debiste
dar el oro que guardabas, y que confiesas no ser tuyo, a los que tanto
lo necesitaban peregrinando tan largo tiempo lejos de su patria; ni aun
ahora quieres soltarlo, sino que persistes en retenerlo; y sin embargo
si hubieses alimentado, como era justo, y defendido a mi hijo, mucha
gloria ganaras, si es cierto que los amigos verdaderos se conocen en la
adversidad, y que la buena fortuna los atrae por sí misma. Si hubieses
necesitado dinero y la suerte te hubiera sido propicia, mi hijo habría
sido rico tesoro para ti, y ahora no puede ser este tu amigo, y has
perdido esas riquezas y tus hijos, y te ves reducido a este extremo. Y
te digo, ¡oh Agamenón!, que si socorres a este, te creerán también
malvado, porque no serás benéfico con un huésped piadoso, ni fiel a
los que debías serlo, ni santo, ni justo; antes bien, diremos que, si lo
haces, es porque te agrada favorecer a los criminales. Pero no quiero
proferir injurias contra mis dueños.
EL CORO

En verdad, en verdad que una buena causa inspira o los hombres


discursos elocuentes.
AGAMENÓN[80]
Molesto es para mi juzgar pleitos ajenos, y, sin embargo, es preciso
porque sería indecoroso aceptar un compromiso y no cumplirlo. Has de
saber, pues, que, en mi concepto, ni por favorecerme, ni por conciliarte
la benevolencia de los aqueos has dado muerte a tu huésped, sino po
guardar su tesoro en tu palacio. Tú hablas como te conviene, obligado
por tus males. Fácil os será, acaso, matar a quienes dais hospitalidad
pero entre nosotros, los griegos, es una infamia. ¿Cómo, pues, si te
absuelvo, evitaré el vituperio? Seguramente no puedo. Pero ya que
osaste cometer lo que no era justo, sufre sus tristes consecuencias.
POLIMÉSTOR

¡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

¡Ay de mí, mísero, de mis hijos y de mis ojos!


HÉCUBA
¿Te lamentas? ¿Y yo? ¿Crees que no lloro al mío?
POLIMÉSTOR

¡Gozas insultándome, oh mujer maliciosa!


HÉCUBA
¿No he de alegrarme, habiéndome vengado de ti?
POLIMÉSTOR

Pero bien pronto se disipará tu gozo, cuando las saladas ondas...


HÉCUBA
¿Me llevarán en las naves hasta los confines de la Grecia?
POLIMÉSTOR

Al contrario, te tragarán cayéndote de lo alto de los mástiles.


HÉCUBA
¿Quién me hará dar tan mortal salto?
POLIMÉSTOR

Subirás por tus pies al mástil.


HÉCUBA
¿Con alas en mis espaldas, o de qué modo?
POLIMÉSTOR

Serás transformada en perra, y tus ojos parecerán de fuego.


HÉCUBA
¿Y cómo sabes que mi forma ha de cambiar?
POLIMÉSTOR

Dioniso, oráculo de los tracios,[81] me lo ha dicho.


HÉCUBA
¿Y no te anunció ninguno de los males que padeces?
POLIMÉSTOR

Nunca hubiese sido víctima de tus asechanzas.


HÉCUBA
Y lo que dices, ¿me sucederá en vida, o después de muerta?
POLIMÉSTOR

Después de muerta, y tu nombre designará tu sepulcro.


HÉCUBA
¿Que signifique mi nueva forma, o de qué manera?
POLIMÉSTOR

Sepulcro de una perra desdichada, y señal para los navegantes.


HÉCUBA
Poco me importa, siempre que me haya vengado de ti.
POLIMÉSTOR

También morirá tu hija Casandra.


HÉCUBA
Caiga sobre ti mi maldición, y ojalá que tú sufras esos males.
POLIMÉSTOR

La matará la esposa de este, cruel defensora de su palacio.


HÉCUBA
Que la hija de Tíndaro no delire hasta ese punto.
POLIMÉSTOR

Y también a Agamenón, levantando segunda vez su segur.


AGAMENÓN
¿Has perdido el juicio, desventurado? ¿Quieres ser víctima de
nuevos infortunios?
POLIMÉSTOR

Mátame, que en Argos te espera el agua lustral de este homicidio.


AGAMENÓN
Llevadlo arrastrando de mi vista, ¡oh servidores!
POLIMÉSTOR

¿Te duele oírme?


AGAMENÓN
¿No le cerraréis los labios?
POLIMÉSTOR

Cerradlos, que ya lo dije todo.


AGAMENÓN
¿Y no lo arrojaréis a alguna isla desierta, ya que tanto ha abusado
de su lengua? (Llévanse a Poliméstor). Tú, desdichada Hécuba, ve a
sepultar tus dos hijos muertos. Encaminaos vosotras, ¡oh tróades!, a
las tiendas de vuestros dueños, que ya sopla el viento favorable que ha
de llevarnos a nuestra patria. ¡Que sea feliz nuestra navegación! ¡Que
libres de tantos infortunios, veamos gozosos a los que dejamos en
nuestros hogares!
EL CORO

A las tiendas y al puerto, amigas, a trabajar como esclavas: la dura


necesidad lo manda.
H I P Ó L I TO

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

Yo soy Afrodita, diosa célebre y venerada en la tierra y en el cielo


propicia a cuantos habitan entre el Ponto Euxino[83] y los confines de
Atlántico y ven la luz del sol, rindiendo homenaje a mi poder, y funesta
a los que se ensoberbecen contra mí. Es conforme a la naturaleza de
los dioses que reciban placer de los honores que se les tributan. Pronto
probaré esta verdad, porque Hipólito, hijo de Teseo, descendiente de
las Amazonas[84] y discípulo del casto Piteo,[85] es el único mortal que
en Trecén[86] se atreve a escarnecerme, diciendo que soy la peor de las
deidades, y odia el lecho nupcial, y no quiere casarse, y rinde culto a
Artemisa, hermana de Febo e hija de Zeus, creyendo que es la diosa
de más poder, y vive siempre en su virginal compañía en la verde
selva, persiguiendo a las fieras con sus ágiles perros, frecuentando su
trato y dándose más que humana importancia. Seguramente no lo
hago por envidia, pues ¿a qué vendría? Pero me vengaré hoy de él
porque me ha ofendido; y como hace ya tiempo que preparo m
venganza, no me será difícil realizarla. Muéveme a ella que cuando
vino del palacio de Piteo al campo de Pandión[87] para asistir a las
fiestas y ceremonias de los sagrados misterios,[88] lo vio Fedra, noble
esposa de su padre, y la inspiré un amor ardiente, y antes de llegar a
Trecén, y en la misma roca de Palas,[89] que mira hacia aquí, edificó
para mí un templo, ardientemente enamorada de Hipólito, que
peregrinaba a la sazón, y en honor suyo quiso que en adelante se
llamase el templo de Afrodita. Pero cuando Teseo abandonó el país de
Cécrope,[90] desterrado en castigo de la muerte de los Palántidas,[91] y
navegó hacia aquí con su esposa para sufrir voluntariamente penosa
relegación, que ha de durar un año, ella no hace más que gemir, y
estimulada por el aguijón del amor, sufre en silencio su desventura, y
ninguno de sus servidores conoce la causa de su mal. Este amor no
dejará de dar su fruto, y yo lo descubriré a Teseo, y se hará público. Y
su padre matará a este enemigo mío, pronunciando terribles
imprecaciones, que cumplirá Poseidón, dios del mar, por haberse
obligado a hacer tres veces lo que le pidiera Teseo. Ínclita es Fedra y
morirá, sin embargo, porque su ruina no pesará tanto en mi ánimo que
consienta en que mis enemigos queden impunes y renuncie a m
propósito. Pero como veo a Hipólito, el hijo de Teseo, que viene hacia
aquí para descansar de las fatigas de la caza, abandonaré estos
lugares. Síguenle multitud de servidores cantando himnos en honor de
Artemisa; no sabe que ya se abrieron para él las puertas de la muerte
y que este será el último día que ha de ver.
HIPÓLITO (que trae una corona,
seguido de sus compañeros de caza).

Seguidme, seguidme cantando en honor de Artemisa, nuestra


protectora celestial, hija de Zeus.
EL SÉQUITO DE HIPÓLITO[92]

Salve, diosa muy augusta, hija de Zeus, digna, digna de veneración


salve, Artemisa, hija de Leto y de Zeus, la más hermosa de las
vírgenes, que en el vasto cielo habitas en el ilustre palacio paterno
resplandeciente con el oro de Zeus.
HIPÓLITO (dirigiéndose hacia la estatua de Artemisa).

Salve, ¡oh bellísima, bellísima Artemisa!, virgen que moras en e


Olimpo: para ti traigo esta corona tejida de flores no libadas, que la
adornan, y cogidas por mí en donde el pastor no se atreve a llevar sus
rebaños ni ha entrado jamás el hierro: solo la primavera visita este
prado y las abejas no le tocan, y el pudor lo nutre con húmedo rocío
El que nada adquirió con el estudio y en todo es igualmente casto po
naturaleza, puede cortar sus flores, no los malvados. ¡Oh dueña
querida!; recibe esta corona de mis manos piadosas para engalanar tus
cabellos de oro. Solo entre los mortales disfruto de este privilegio; a tu
lado estoy siempre, contigo hablo, y escuchas mi voz, aunque no vea
tu rostro. Como he empezado, así acabaré mi vida.
UN SERVIDOR (que se separa del coro).
¡Oh rey!, puesto que a nuestros señores debemos llamar como a los
dioses,[93] ¿quieres oír un consejo útil?
HIPÓLITO

Con mucho gusto: si no lo hiciera, no parecería sabio.


SERVIDOR
¿Conoces una ley que ha de regir a los mortales?
HIPÓLITO

No; ¿a qué ley aludes?


SERVIDOR

A la que nos manda evitar la ostentación y lo que no sea grato a


todos.
HIPÓLITO

Muy bien dicho; en verdad, ¿qué hay más repugnante que e


hombre orgulloso?
SERVIDOR
En la urbanidad, ¿no se nota cierta gracia, que nos concilia la
benevolencia de las gentes?
HIPÓLITO

Mucha, sin duda, y ofrece largo lucro con poco trabajo.[94]


SERVIDOR
¿Y crees que con los dioses sucede lo mismo?
HIPÓLITO

Sí, porque los hombres, obrando así, obedecen las leyes divinas.[95]
SERVIDOR
¿Y por qué tú no saludas a una diosa veneranda?
HIPÓLITO

¿A cuál? Guárdate de ofenderme.


SERVIDOR
A Ciprina, la que preside a tus puertas.[96]
HIPÓLITO

Como estoy puro, la saludo desde lejos.


SERVIDOR

Pero es digna de veneración, e insigne entre los mortales.


HIPÓLITO

Cada dios y cada hombre eligen recíprocamente al que mejor les


parece.
SERVIDOR

Que seas feliz, si sabes cuanto te interesa.


HIPÓLITO

No me agradan los que reverencian de noche a los dioses.


SERVIDOR
Necesario es, ¡oh joven!, darles culto.
HIPÓLITO

Id, compañeros, y cuidad en el palacio de preparar nuestro


sustento, que es grata una mesa abundante después de la caza, y
conviene que los caballos se repongan de sus fatigas, para que a
uncirlos al carro, satisfecho mi apetito, lo rija sin trabajo; que tu
Ciprina se conserve buena mucho tiempo. (Retírase con su séquito).
SERVIDOR (ante la estatua de Afrodita).
Por lo que hace a mí, que no debo imitar a los jóvenes, y pensando
humildemente como siervo, adoro tu imagen, ¡oh Afrodita!, señora
mía; perdona al que así delira hablando de ti, porque siento hervir en
su pecho el fuego de la adolescencia;[97] disimula si lo oyes, que los
dioses han de ser más prudentes que los hombres.
EL CORO (que viene del campo).

Estrofa 1.ª — Fama tiene un peñasco a la orilla de la mar, que


destila agua, del cual brota una fuente en donde se llenan las urnas
Cierta compañera mía lavaba allí vestidos de púrpura, y los ponía a
secar después en el peñasco abrigado y tibio.[98]
Antístrofa 1.ª — Ella, la primera, me contó el rumor de que m
dueña no salía de su palacio, consumiéndose en doliente lecho, y que
sutiles telas velaban su cabeza. Tres días hace ya, según he oído, que
su boca no saborea los frutos de Deméter ni se alimenta su cuerpo, y
que oculta pena la arrastra a desear la muerte, término de su mísera
existencia.
Estrofa 2.ª — Sin duda te ha tocado Pan, ¡oh joven!, o Hécate, o los
venerables coribantes, o la madre que recorre los montes, y por eso
deliras.[99] Acaso pecaste contra Dictina,[100] que vive gozosa entre las
fieras, y no le has ofrecido sacrificios ni libaciones, y por esto te
consumes, que también ella atraviesa los mares y va más allá de la
tierra, en los salados remolinos del húmedo piélago.
Antístrofa 2.ª — ¿Acaso tu marido, el primero de los hijos de
Erecteo, noble varón, se deleita en tu palacio profanando tu lecho con
ilícitos amores? ¿Ha navegado algún marinero desde Creta[101] a este
puerto, el más hospitalario, trayendo a la reina algún fatal mensaje, y
esa es la causa de su tristeza, y de que yazga en su lecho y esté
afligido su corazón?
Epodo. — Solo en las mujeres se ven juntas la frivolidad natural a
su sexo y cierta propensión a la melancolía, tan perjudicial como
molesta, ya por temor a los dolores del parto, ya por su innata
demencia. Por mis entrañas discurrió alguna vez este aura, e invoqué a
la diosa que nos ayuda en tan apurado trance, a Artemisa, diestra en
disparar sus saetas, y siempre propicios los dioses, me favoreció
mucho en mis trabajos. Pero he aquí a la vieja nodriza que la saca de
palacio: triste nube se mece en torno de sus cejas. Quisiera saber la
causa funesta que ha alterado la salud de la reina. (Las esclavas traen
a Fedra recostada en un lecho portátil).
LA NODRIZA

¡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).

Levantad mi cuerpo, sostened mi cabeza; no tengo fuerzas para


mover mis miembros, ¡oh amigas! Acercaos, servidoras, y apoyaré mis
brazos dulcemente. Pésame la diadema en las sienes; quítala, que mis
cabellos se esparzan por mis hombros. (Dos esclavas sostienen a Fedra
en los brazos; la nodriza recibe en su pecho la cabeza y le quita la
diadema).
LA NODRIZA

Ten ánimo, ¡oh hija!, y no te agites, que así se agravará tu


padecimiento. Más tolerable será descansando tranquila y sufriendo
con noble resignación: ley es de los mortales luchar con los dolores.
FEDRA

¡Ay, ay! ¡Ojalá que yo beba agua cristalina de fresca fuente, y que
bajo blancos álamos y en verde prado yazga reclinada!
LA NODRIZA

¿Qué dices, hija? No hables así delante de esta gente, ni profieras


palabras insensatas.
FEDRA (delirando y agitándose inquieta en su lecho).

Llevadme a las selvas; que vaya yo a los bosques y a los pinares, en


donde corren los perros que matan a las fieras, saltando sobre los
manchados ciervos; deseo, por los dioses, animarlos con mis gritos, y
lanzar el dardo tesálico rozando con mi blonda cabellera, y vibrar en m
mano la saeta de acerada punta.
LA NODRIZA

¿Por qué, ¡oh hija!, revuelves esto en tu ánimo? ¿A qué cuidarte


ahora de la caza? ¿A qué apetecer las ondas de las fuentes? Cerca de
palacio hay una colina húmeda, en donde puedes beber a tu gusto.
FEDRA

¡Oh Artemisa!, señora de la marina Limnes[102] y de los ecuestres


gimnasios: ¡ay, si estuviera en tu campo domando caballos vénetos![103
LA NODRIZA

¿Por qué, delirando de nuevo, pronuncias tales palabras? Hace poco


que, como si te hallaras en los montes, te arrastraba la afición a la
caza; ahora, segunda vez, y lejos de las ondas, deseas regir caballos
Adivino consumado es preciso ser para explicar todo esto: ¿qué dios
¡oh hija!, te hace tascar el freno y extravía tu juicio?
FEDRA (cayendo abatida en su lecho).
¡Infeliz de mí! ¿Qué he hecho? ¿Cuál ha sido mi absurdo delirio? He
perdido la razón, he caído en las redes de alguna deidad funesta. ¡Ay
ay mísera de mí! Nodriza, cubre otra vez mi cabeza; me avergüenzo de
lo que he dicho hace poco. Cúbrela; lágrimas brotan de mis ojos, y e
pudor enrojece mis párpados. Porque he recobrado el seso, y el dolo
me atormenta, y si la locura es un mal, más vale morir sin sentirla.
LA NODRIZA

Ya la cubro; pero ¿cuándo la muerte velará también mi cuerpo?


(Cubre su cuerpo y se dirige al público). Mucho me enseña mi larga
vida; convendría que los mortales no contrajesen amistades estrechas
de las que penetran hasta lo íntimo del alma, y así sería fácil que se
desvaneciese esta pasión, y que, como nace, muriese. Pero que uno
sufra por dos, es grave carga, como a mí me acontece, sufriendo po
esta.[104] Dícese que el excesivo apego a la vida aflige más que deleita
y que es opuesto a la salud; pero los excesos son para mí menos
laudables que practicar aquel otro precepto de nada demasiado y
como yo opinarán los sabios.
EL CORO

¡Oh anciana, fiel nodriza de la reina Fedra!; aunque sea testigo de


estas calamidades, es para mí inexplicable su enfermedad; quisiéramos
oírla y saberla de ti.
LA NODRIZA
Ni preguntándolo lo sé, ni quiere decirlo.
EL CORO

¿Ni cuál haya sido el origen de estos males?


LA NODRIZA
Piensas como yo; pero ella lo calla todo.
EL CORO

¡Qué enferma está, y cuán flaco su cuerpo!


LA NODRIZA

¿Y cómo no ha de ser así, si hace tres días que no toma alimento?


EL CORO

¿Pero es efecto de su mal, o porque desea morir?


LA NODRIZA

Por morir; se abstiene del alimento por dejar la vida.


EL CORO

Sorprendente es lo que has dicho, si agrada a su marido.


LA NODRIZA
Oculta y niega su dolencia.
EL CORO

¿Pero no la conoce él si le basta mirarla?


LA NODRIZA
Lejos está ahora.
EL CORO

¿Y tú no la violentas para averiguar su mal y la causa del extravío


de su juicio?
LA NODRIZA

Vanos han sido todos mis esfuerzos. Sin embargo, aún no he


desistido de mi propósito, como te habrás convencido, observando lo
que hago con mi desventurada dueña. (A Fedra). Vamos, hija querida
olvidémonos ambas de lo que antes hablamos, y tú explícate, y
desarruga tu ceño, y abandona tu resolución, y yo, por mi parte, sin
acordarme ya de lo que he hecho hasta ahora que haya podido
desagradarte, te hablaré con más dulzura. Si padeces algún ma
oculto, estas mujeres lo calmarán; pero si lo han de curar los hombres
habla para declararlo a los médicos. Sea, pues, así; ¿por qué callas? No
debes callar, hija, sino replicarme si no te parece bien lo que digo, o
seguir mis consejos si lo merecen. Habla algo, mira hacia aquí. ¡Cuánta
es mi desventura! En vano, ¡oh mujeres!, nos tomamos este trabajo
tan lejos estamos como antes de conseguir nuestro fin: ni le hacían
mella nuestras palabras, ni ahora tampoco. Pero ten en cuenta, aun
cuando seas más obstinada que la mar, que si mueres, abandonando
tus hijos, no participarán de la herencia de su padre y le sucederá e
noble y generoso bastardo, que dio a luz la reina Amazona aficionada a
cabalgar, y será su señor. Bien sabes de quién hablo: ya sabes que
aludo a Hipólito.
FEDRA

¡Ay de mí!
LA NODRIZA
Qué, ¿te interesa esto?
FEDRA

Me has afligido, nodriza, y te ruego por los dioses que jamás me


hables de ese hombre.
LA NODRIZA
¿Ves? Eres prudente, y no querrás faltar a tus hijos, y cuidarás de tu
vida.
FEDRA

Amo a mis hijos; pero no es ese el mal que me atormenta.


LA NODRIZA

Sin duda, ¡oh hija!, tus manos están puras de sangre.


FEDRA

Puras están mis manos, pero no mi corazón, y es meneste


purificarlo.
LA NODRIZA

¿Quizá por efecto del daño que te ha causado algún enemigo?


FEDRA

Contra su voluntad y la mía me ha perdido un amigo.


LA NODRIZA

¿Te ha faltado en algo Teseo?


FEDRA

¡Ojalá que yo nunca le ofendiera!


LA NODRIZA
¿Y cuál es esa pena cruel que te hace morir?
FEDRA

Deja que yo falte; no eres tú la ofendida.


LA NODRIZA
No, seguramente; líbrenme los dioses de pensarlo; pero tú puedes
salvarme. (Arrójase a sus pies y estrecha sus manos y rodillas).
FEDRA

¿Qué intentas? ¿Me haces violencia estrechando mi mano?


LA NODRIZA
Y nunca soltaré tus rodillas.
FEDRA

Lo sentirás, ¡oh desventurada!; lo sentirás si lo oyes.


LA NODRIZA

¿Qué mayor sentimiento que perderte?


FEDRA

Morirás, y sin embargo puede darme gloria.


LA NODRIZA
¿Y me ocultas este bien, cuando yo te lo suplico?
FEDRA

A males que me avergüenzan busco salida honesta.


LA NODRIZA
Luego si los declaras será mayor tu ventura.
FEDRA

Retírate, por los dioses, y suelta mi mano.


LA NODRIZA

Jamás, si no me concedes lo que tan justamente pido.


FEDRA

Lo haré, porque como religioso vínculo es para mí tu mano.


LA NODRIZA
Callaré ya; ahora tú debes hablar.
FEDRA (después de algunos instantes de silencio).

¡Oh mísera madre, cuáles fueron tus amores![105]


LA NODRIZA
¿Lo dices porque se enamoró del toro, o por qué?
FEDRA

¡Y tú, hermana desventurada, esposa de Dioniso![106]


LA NODRIZA
¿Qué te sucede, oh hija? ¿Hablas mal de tus parientes?
FEDRA

¡Y yo, tercera desdichada, que muero de pena!


LA NODRIZA

Horrorizada estoy en verdad. ¿Adónde irá a parar esto?


FEDRA

¡Y yo después, y no hace poco tiempo, soy también infeliz!


LA NODRIZA
Hasta ahora nada sé de lo que anhelo oír.
FEDRA

¡Ay de mí! ¿Cómo me dirías tú lo que yo debo decir?


LA NODRIZA
No soy adivino para comprender estos enigmas.
FEDRA

¿Qué cosa es el amor? ¿Qué dicen de él los hombres?


LA NODRIZA

Lo más dulce, ¡oh hija!, y al mismo tiempo lo más amargo.


FEDRA

No es eso lo que yo sufro.


LA NODRIZA
¿Amas, ¡oh hija!, a alguno?
FEDRA

Cualquiera que sea, el hijo de la amazona...


LA NODRIZA
¡Hablas de Hipólito!
FEDRA

Tú lo dices, no yo.
LA NODRIZA

¡Ay de mí, oh hija! ¿Qué has dicho? ¡Cómo has desgarrado m


corazón! Esto es intolerable, ¡oh mujeres! Ya no puedo vivir. ¡Día
odioso, odiosa luz es la que veo! Yo me despeñaré, yo abandonaré m
cuerpo, yo dejaré esta triste vida; vivid vosotras, que yo aborrezco la
existencia. Los que se contienen, aunque involuntariamente, aman, sin
embargo, sus propios males. No es diosa Afrodita, sino más que diosa
y la ha perdido, y a mí, y a esta familia.
EL CORO
¿Has oído, ¡oh!, has oído a la reina confesando sus malhadados
amores, que no deben escucharse? Que muera yo, ¡oh amada!, antes
de cometer el delito que embarga tu pensamiento. ¡Ay de mí! ¡Oh
desventurada víctima de estos dolores! ¡Oh penas, alimento de los
hombres! Tú misma te has perdido publicando tu mal. ¿Cuánto tiempo
vivirás así? Alguna novedad va a ocurrir en este palacio. Ya no
ignoramos, ¡oh desdichada joven cretense!, en dónde descargará la
tempestad que Afrodita envía.
FEDRA

Mujeres trecenias que habitáis en este vestíbulo,[107] que da entrada


a la tierra de Pélope: hace ya largo tiempo que reflexioné una noche
en las causas de la corrupción humana, y me parece que no todos los
hombres cometen las faltas más graves por sus escasas luces, porque
en muchos se observa juicio recto; preciso es, por tanto, confesar que
aun conociendo lo bueno, no lo seguimos, unos por pereza y otros
porque posponemos la virtud al deleite.[108] Muchos placeres ofrece la
vida, gratos coloquios y ocio, mal que tiene su encanto, y vergüenza
Esta es de dos clases: una no vituperable, azote la otra de las familias
Y si las ocasiones en que se manifiestan no diesen lugar a dudas, no
serían iguales las dos palabras que las expresan. Y como he pensado
antes todo esto, no hay poder bastante fuerte que me obligue a
adoptar la opinión contraria. Pero te diré cómo he llegado a discurri
así. Después que el amor me hirió, traté de conciliarlo con la virtud, y
comencé entonces a ocultar mi dolencia. No debía fiarlo a la lengua
que, si a veces rectifica los pensamientos ajenos, se expone otras a
muchos males. Determiné resistir con entereza a este amoroso delirio
y dominarlo castamente. Por último, no pudiendo vencer a Afrodita, he
decidido morir. Nadie se opondrá a esta resolución. ¡Ojalá que no se
olviden mis acciones honestas, ni que las presencien muchos testigos
si son vergonzosas! No ignoraba cuán infame era mi apasionada
dolencia, y sabía además que era mujer detestada de todos.[109] Mala
muerte tenga la que mancille el lecho conyugal con quien no fuese su
esposo. De las mujeres nobles pasó este mal a las demás, porque
cuando lo torpe agrada a los de elevada alcurnia, parece a los malos
honesto. Odio a las que son castas en sus palabras y ocultamente
lascivas. ¿Cómo, ¡oh Afrodita!, señora del mar,[110] se atreven a mirar e
rostro de sus esposos y no tienen horror a las tinieblas, cómplices de
sus culpas? ¿Cómo no dan voces los techos de sus casas? Mátame, ¡oh
amigas!, el temor de que mi marido sepa mi deshonra, o los hijos que
he parido, pues quisiera que, libres y hablando sin temor, brillasen en
la noble ciudad de los atenienses honrados en memoria de las virtudes
de su madre, porque detiene mucho al hombre más osado saber las
maldades de sus padres. Dicen que vale tanto como vivir ser justo y
honesto. El tiempo descubre a los malos cuando llega la ocasión, como
el espejo que refleja a la virgen. ¡Ojalá que nunca me cuenten entre
ellos!
EL CORO

¡Ay, ay de mí! ¡Qué bella es la modestia y qué gloria tan egregia


ofrece a los mortales!
LA NODRIZA
Gran temor, ¡oh señora!, me ha infundido de repente tu mal; ahora
conozco mi ineptitud, y que entre los hombres los últimos
pensamientos son los más prudentes. No es extraño lo que te sucede
ni fuera de razón se ha ensañado en ti la ira de la diosa. Tú amas; ¿po
que nos ha de sorprender? Haces lo que muchos. ¿Y perderás la vida
por eso? ¿De qué sirven a los enamorados sus amigos, y la inquietud
que muestran, si al fin han de morir? Porque Ciprina es intolerable s
nos ataca con violencia; a quien cede, persigue blandamente, y
arrebata y atormenta al orgulloso y arrogante; ¿no lo crees así? Vuela
por los aires, y la hallarás en las olas del mar, y de todo es origen. Ella
inspira y alimenta al Amor, que a todos nos ha engendrado en esta
tierra. Cuantos conocen los escritos antiguos y se consagran
asiduamente al culto de las musas, saben cómo Zeus amó en otro
tiempo a Sémele,[111] y cómo la brillante Aurora robó enamorada a
Céfalo,[112] llevándolo con los demás dioses, y habitan en el cielo, y no
huyen de las demás divinidades, sino que, según creo, sufren vencidos
su suerte. ¿Y tú no la sufrirás? Debió engendrarte tu padre de distinta
manera que los demás, y obedecerías a otros dioses si no habías de
observar estas leyes. ¿Cuántos hombres de sano juicio fingirán ignora
la deshonra de su cónyuge? ¿Cuántos padres no protegen los amores
ilícitos de sus hijos? Entre las sagaces precauciones de los hombres
cuéntase la de ocultar lo que no es honesto. Ni conviene que vivan
vida austera, como no cuidan tampoco de alinear con esmero las
paredes y el techo de sus viviendas. Del abismo tan profundo en que
has caído, ¿cómo piensas salir? Grande es tu ventura si, siendo mortal
son más numerosos tus bienes que tus males. Abandona, pues, ¡oh
amada hija!, tus malos pensamientos; déjate de tales sacrilegios, que
lo es sobreponerte a los dioses; sufre el amor con fortaleza, que una
diosa lo envía. Ya que esa dolencia te aqueja, cúrala dulcemente. Hay
encantos y palabras que la aplacan, y podrá encontrarse eficaz
remedio. Tarde hallará algún hombre la medicina si nosotras las
mujeres no la descubrimos.
EL CORO

Lo que esta dice, ¡oh Fedra!, puede servirte ahora, y yo te alabo


Pero mi alabanza es para ti menos grata que sus palabras, y la oirás
con más trabajo.
FEDRA
Con pláticas demasiado sabrosas se han arruinado familias y
ciudades bien gobernadas. No conviene decir lo que agrada a los
oídos, sino lo que puede traer gloria.
LA NODRIZA

¿Por qué hablas tan sublime lenguaje? Tú no necesitas de palabras


seductoras, buenas solo para ese hombre. Yo lo sondearé cuanto
antes, y le hablaré como es debido. Si no peligrase tu vida en este
trance y fueses mujer de juicio, jamás llegaría yo a ese extremo po
proporcionarte ese deleite en tu lecho; pero ahora mi principal objeto
es salvar tu vida, y nadie podrá reprobarlo.
FEDRA

¿Cómo dices tales despropósitos? ¿No cerrarás tus labios y no


volverás a pronunciar frases tan torpes?
LA NODRIZA
Torpes son, pero más convenientes ahora que las honestas, y
valdrán más si te salvare que la fama con que morirías orgullosa.
FEDRA

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

Y ese filtro, ¿se unta o se bebe?


LA NODRIZA
No lo sé; es menester que me ayudes y no me preguntes, ¡oh hija!
FEDRA

No es para tranquilizarme tu refinada astucia.


LA NODRIZA
Todo te asusta; ¿qué temes ahora?
FEDRA

Que reveles algo al hijo de Teseo.


LA NODRIZA
Déjame, hija, que yo te curaré bien. Solo te ruego que me
favorezcas, ¡oh Afrodita, diosa marina! (Aparte). Lo demás que pienso
hacer lo sabrán únicamente los amigos que hay dentro.[114] (Se retira).
EL CORO

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é sucede en tu palacio, ¡oh Fedra!?


FEDRA

Estaos quietas; dejadme oír los clamores que suenan dentro.


EL CORO

Callo; pero mal exordio es este.


FEDRA

¡Ay de mí! ¡Ay de mí! ¡Cuánta es mi desventura! ¡Cuántos mis


males!
EL CORO

¿Qué significan tus quejas? ¿Qué tus voces? Di, ¡oh mujer!, ¿qué
súbito rumor te atorra?
FEDRA

Perdidas somos. Acercaos aquí, y escuchad el ruido que se oye


dentro.
EL CORO
Tú estás a la puerta; en cuidado te han puesto los clamores que
salen del palacio. Pero dime, dime qué desgracia sucede.
FEDRA

Grita Hipólito, el hijo de la Amazona, aficionada a cabalgar


profiriendo horribles maldiciones contra mi esclava.
EL CORO
Conozco su voz, pero no entiendo bien lo que dice. Por las
hendiduras de la puerta oirás tú sus palabras.
FEDRA

Y oigo claramente que la llama forjadora de males, y que la acusa


de hacer traición a su dueño.[117]
EL CORO
¡Ay de mis desdichas! Te han vendido, ¡oh amiga! ¿Qué consejo te
daré? Si ha descubierto el secreto, cierta es tu muerte.
FEDRA
¡Ay, ay de mí!
EL CORO

Vendida por tus amigos.


FEDRA

Me ha perdido descubriendo mi dolencia, con buena intención, es


verdad, pero sin curarla como debía.
EL CORO

¿Y qué se hace? ¿Qué harás tú, que sufres males incurables?


FEDRA

Solo me ocurre morir cuanto antes, único remedio de este


infortunio.
HIPÓLITO (que sale por una de las puertas laterales, seguido de la nodriza. Como Fedra
se halla en el hueco de la principal, y lejos, no la ve).

¡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

No es posible callar, habiendo oído tales horrores.


LA NODRIZA (suplicándole humildemente).
Suplícote por tu barba y tu hermosa diestra.
HIPÓLITO (rechazándola).

No acerques tu mano ni toques mi vestido.


LA NODRIZA (echándose a sus pies).

¡Por tus rodillas, que abrazo, no me pierdas!


HIPÓLITO

¿Y cómo así, cuando, según aseguras, no has dicho nada malo?


LA NODRIZA
Lo que yo he dicho, ¡oh hijo!, no debe saberlo el vulgo.
HIPÓLITO

Mejor es, sin embargo, que el vulgo solo sepa lo bueno.


LA NODRIZA
¡Oh hijo!, no quebrantes tu juramentos.
HIPÓLITO

La lengua juró; el alma no ha jurado.[118]


LA NODRIZA
Hijo, ¿qué vas a hacer? ¿Perderás a tus amigos?
HIPÓLITO

Les niego ese nombre: ningún malvado es mi amigo.


LA NODRIZA
Perdona; siempre han errado los hombres, ¡oh hijo!
HIPÓLITO (dirigiéndose al público, mientras la nodriza se levanta).[119]

¡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

Mísera y desventurada es nuestra suerte. ¿Qué artes emplearemos


qué recursos, frustrada nuestra esperanza, para desatar el nudo de
esta intriga? Recibimos el castigo merecido, ¡oh tierra y luz! ¿Cómo
evitaré estas calamidades? ¿Cómo, ¡oh amigas!, ocultaré mi mal? ¿Qué
dios me favorecerá, qué hombre me ayudará? ¿Quién querrá hacerse
cómplice de maldades tan impías? No veo medio alguno de alejar la
tempestad que amenaza a mi vida. ¡Soy la más infeliz de las mujeres!
EL CORO
¡Ay, ay! Ya no tiene remedio, y de nada sirvieron los artificios de tu
esclava, ¡oh señora!, que el resultado ha sido desastroso.
FEDRA (acércase a Fedra la nodriza).

You might also like