Tải bản đầy đủ (.pdf) (442 trang)

molkentin-the book of qt 4-the art of building qt applications

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.37 MB, 442 trang )

Cross-platform development is a kind of holy grail, and
Trolltech’s Qt toolkit may well be the most promising
solution yet to this development challenge. Qt is widely
used for the development of GUI applications as well
as console tools and servers, and it’s especially appeal-
ing to programmers who need to write cross-platform
applications to run on Linux/Unix, Mac, and Windows
machines without having to rewrite for each platform.
The Book of

Qt 4 offers an in-depth explanation of Qt
4 that goes beyond the common focus on C++ program-
ming. Author Daniel Molkentin uses practical examples
to explain features like the signal/slot concept and the
event system, as he guides you through developing
applications with and without Qt’s graphical GUI builder,
Qt Designer. And as a core KDE developer, Molkentin’s
head is full of real-world problems and solutions that he
peppers liberally throughout The Book of Qt 4, making
it a resource that you’ll consult time and again.
You’ll find coverage of:
• Tools for creating dialogs
• GUI design with the Qt Designer
• Widget layout and dialog construction
www.nostarch.com
THE FINEST IN GEEK ENTERTAINMENT

SHELVE IN:
PROGRAMMING
$54.95 ($65.95 CDN)
• Data visualization using Qt’s model/view concept


• The QtSql module and the graphics library Arthur
• File handling, XML, processes, and network connections
• Databases and threading
• Event handling and using drag and drop
• Internationalization and debugging
As well as lots of useful hints on how to use Qt’s data-
types, containers, and algorithms and how to develop
user-friendly applications.
Whether you’re already a Qt developer or you’re just
considering Qt for cross-platform development, you’ll
find The Book of Qt 4 to be indispensable.
ABOUT THE AUTHOR
Daniel “danimo” Molkentin has been a core developer
with the KDE project since 2000, and he’s the co-author
of the PIM application Kontact, among other applications.
He was actively involved in the development of Qt 4 as a
beta tester, and he worked with the initial port of KDE to
the new Qt version.
Qt 4. FROM THE
BASICS THROUGH
APPLICATION
DESIGN.
Qt 4. FROM THE
BASICS THROUGH
APPLICATION
DESIGN.
“I LAY FLAT.”
This book uses RepKover— a durable binding that won’t snap shut.
Printed on recycled paper
Qt 4

Qt 4
THE ART OF BUILDING Qt APPLICATIONS
DANIEL MOLKENTIN
THE BOOK of
THE BOOK of
Qt 4
THE
BOOK
of
THE
BOOK
of
Qt 4
®
MOLKENTIN

The Book of Qt 4

Daniel Molkentin
TheBook of Qt 4
TheArt of BuildingQtApplications
®
Munich SanFrancisco
The Book of Qt 4: The ArtofBui ldingQtApplications. Copyright
c
 2007OpenSource PressGmbH
Allrightsreserved.Nopartofthisworkmaybe reproducedortransmittedinanyform or byanymeans, electronic or
mechanical, includingphotocopying, recording, or byanyinformationstorageorretrieval system,without theprior
writtenpermission of thecopyright ownerand thepublisher.
Printedonrecycled paperinthe United States of Am erica.

12345678910—10090807
No Starch Pressand theNoStarch Presslogo areregisteredtrademarksofNoStarch Press, Inc. Otherproduct and
companynamesmentioned herein maybe thetrademarksoftheir respectiveowners .Ratherthanuse atra demark
symbol witheveryoccurrence of atrademarked name,weare usingthe na mesonlyin an editorialfashionand to the
benefit of thetrademark owner, withnointention of infringement of thetrademark.
Publisher: William Pollock
Cover Design:Octopod Studios
U.S. editionpublishedbyNo Starch Press, Inc.
555 De HaroStreet,Suite 250,San Francisco, CA 94107
phone: 415.863.9900;fax:415.863.9950;;
Original edition
c
 2006OpenSource PressGmbH
PublishedbyOpenSource PressGmbH, Munich, Germany
Publisher: Dr.Markus Wirtz
Original ISBN 978-3-937514-12-3
For informationontranslations, pleasecontact
OpenSource PressGmbH, Amalienstr.45Rg, 80799 M
¨
unchen, Germany
phone+49.89.28755562; fax+49.89.28755563; ;
Theinformationinthisbook is distributed on an “AsIs” basis, without warranty.While everyprecaution hasbeen
takeninthe preparationofthiswork, neitherthe author norOpenSource PressGmbHnor No Starch Press, Inc. shall
haveanyliabilityto anyperson or entitywithrespect to anyloss or damage caused or allegedtobecaused directly
or indirectlybytheinformationcontained in it.
LibraryofCongressCataloging-in-Publication Data
Molkentin, Daniel
[Qt4, Einf¨uhrung in die Applikationsentwicklung.English]
The book of Qt4: the art of building Qtapplications/byDaniel Molkentin
1st ed.

p. cm.
Includesindex.
ISBN-13978-1-59327-147-3
ISBN-101-59327-147-6
1.Qt(Electronic resource)2.Graphicaluserinterfaces(Computersystems) 3.
Application software Development. I.Title.QA76.9.U83M62132007
005.4’37 dc22
2007013181
Contents
Introduction 19
Preparations23
1Basics, Tools, andFirst Code 25
1.1Our FirstQtProgram 25
1.1.1CompilingaQtProgram 27
1.2Layouts,Object Hierarchy,and MemoryManagement 29
1.2.1Howto ArrangeWidgets Automatically 29
1.2.2MemoryManagement in Object Hierarchies 31
1.2.3Other LayoutTypes 33
1.3Signals andSlots 35
1.3.1The Sim plestCase: ASlotResponds to aSignal 35
1.3.2Signals CarryingAdditional Information andHowThey
AreProcessed 36
1.4BaseClassesinQt 39
1.4.1ClassesDerived from QObject 39
1.4.2QString andOther Classesnot Derived from QObject 40
1.4.3The Qt InheritanceHierarchy 41
1.5QtataGlance 42
1.5.1The Qt Libraries 42
1.5.2Toolsand Utilities 47
1.5.3Examples andDemos 58

1.6Howto Use theDocumentation 59
5
Contents
2The ToolsNeeded to Create Dialogs61
2.1What’sthe DifferenceBetween Dialogsand Widgets? 62
2.1.1Inheriting from QObject 64
2.1.2MoreComplexLayouts 65
2.1.3IncreasingUsability 68
2.1.4ImplementingSlots 70
2.2SeparationofGUI andProcessing Logic 74
2.2.1AlternativeDesign 74
2.2.2Declaring andSending OutSignals 76
2.2.3Using Your OwnSignals 79
3GUI Design Using theQtDesigner81
3.1Dialogs “ByMouseClick” 81
3.1.1Making La youts With theDesigner 84
3.1.2The PropertyEditor. 85
3.1.3The Preview 88
3.1.4Signal/SlotConnections 88
3.1.5The TabSequence 89
3.1.6Shortcuts andBuddies 90
3.2Integrating Designer-generated FilesintoYourQtProject 91
3.2.1Using Designer-generated ClassesasHelperClasses 92
3.2.2AlwaysHavingDesigner-generated Widgets Available 94
3.2.3MultipleInheritance 95
3.3Automatic Signal/SlotConnections 97
3.4Including Derived Classesinthe Designer 99
3.5The Resource Editor 99
4Developing aGUI Application BasedonaMain Window 101
4.1The Anatomyof theMainWindow 101

4.2DerivingfromQMainWindow 103
4.3CreatingaMain Windowwiththe Qt Designer 106
4.3.1Adding Menu Bars 107
4.3.2RecyclingActions in theToolbar 108
6
Contents
4.3.3Integrating theMainWindowwithYourSourceCode 110
4.4Making theMostofthe Status Bar 118
4.4.1TemporaryMessages 120
4.4.2NormalMessages. 120
4.4.3Permanent Messages. 121
4.5Toolbars 125
4.6HowDo ActionsWork? 126
4.6.1Howto InstantiateQAction Manually 127
4.6.2Selectable Actions 128
4.6.3Grouped Actions 128
4.7DockWindows 130
4.7.1Positioning Dock Windows. 131
4.7.2ADock Windowfor OurEditor 133
4.8SavingPreferences 136
4.8.1Extending CuteEdit 139
5Laying OutWidgets 141
5.1ManualLayout 141
5.2Automatic Layout 143
5.2.1Horizontaland Vertical Layout 144
5.2.2GridLayout 148
5.2.3Nested Layouts 149
5.3Splitter 150
5.3.1BehaviorDuringSizeChanges 150
5.3.2SavingSplitter Positionsand Determining theWidgetSize151

5.3.3Defining RelativeSizes 152
5.3.4CustomizingHandles 153
5.3.5Layoutfor LanguagesWritten from RighttoLeft 156
5.4StackedLayouts 157
5.4.1The Alternative: Stacked Widgets 157
5.4.2WhentoUse Stacked Layouts andWidgets 157
7
Contents
6Dialogs161
6.1Modal Dialogs 161
6.2Non-modal Dialogs 163
6.2.1UsabilityProblems 163
6.3Semi-modal Dialogs 164
6.4Avoiding Bloated Dialogs 164
6.5Ready-made DialogsinQt 166
6.5.1Message Dialogs 166
6.5.2Error MessagesThatAre OnlyVisible Once 174
6.5.3File SelectionDialogs 175
6.5.4Input Dialogs 179
6.5.5FontSelection Dialog 182
6.5.6Color Selectionand Printing Dialog 183
7Events, Drag andDrop, andthe Clipboard185
7.1EventLoop andEventHandler 185
7.2HandlingEvents 186
7.2.1Using Specialized EventHandlers 186
7.2.2Using theGeneral EventHandler 189
7.3Using EventFilters 190
7.4Dragand Drop 194
7.4.1MIMETypes 194
7.4.2The Drag Side 196

7.4.3The Drop Side. 198
7.5The Clipboard 201
8Displaying Data Using “Interview”207
8.1UnderlyingConcepts 208
8.1.1The ViewClasses 210
8.1.2The Model Classes 211
8.2DisplayingDirectoryHierarchies 212
8.2.1Using ViewClassesinthe Designer 214
8.2.2Implementingthe Fu nctionalityof theFile SelectionDialog216
8
Contents
8.3The String ListsModel 221
8.4ImplementingYourOwnModels 222
8.4.1AnAddressBook Model 222
8.4.2Making Your OwnModels Writable 227
8.5Sorting andFilteringDatawithProxy Models 231
8.5.1Adjustments to theUserInterface 232
8.6Making EntriesSelectable withCheckboxes 234
8.7Designing Your OwnProxy Models 237
8.8ImplementingDragand Drop in Models 241
8.9YourOwnDelegates 245
8.10WithoutYourOwnDataSource: TheStandardModel. 249
8.11 Element-basedViewsWithout Model Access 251
8.11.1Items 251
8.11.2The List View 251
8.11.3The Tree View 252
8.11.4The Table View 253
8.11.5Cloning Items. 254
9The QtSqlModule 257
9.1Structure of theQtSql Module 257

9.2Selecting theAppropriate Driver 258
9.3Making aConnection 260
9.4Making Queries 261
9.5Transactions 264
9.6EmbeddedDatabases 264
9.7Using SQLModelClasseswithInterview 265
9.7.1DisplayingSQL TablesWithout ForeignKeysinTable and
Tree Views. 265
9.7.2ResolvingForeign KeyRelations 266
9.7.3DisplayingQueryResults. 267
9.7.4Editing St rategies. 268
9.7.5Errorsinthe Table Model 270
9
Contents
10 TheGraphicsLibrary “Arthur”271
10.1 Colors. 271
10.1.1 TheRGB Color Space 272
10.1.2 Other Color Spaces 273
10.1.3 Color SelectionDialog 275
10.2 Painting withQt 276
10.3 Geometrical Helper Classes 278
10.4 Howto PaintonWidgets 280
10.4.1 Howto PreventMonitor Flicker 282
10.5 Using QPainter in Practice 283
10.5.1 DrawingaPieChart 284
10.5.2 Definingthe Wi dgetSize 289
10.5.3 TheDiagram Application 290
10.6 Transformationsofthe CoordinateSystem 290
10.6.1 TransformationsinPractice 293
10.7 QImage 297

10.7.1 Storage Formats, Transparency,and Color Palettes 297
10.7.2 Reading outPixelsLinebyLine 298
10.8 SVGSupport 300
10.9 Printing withQPrinter 302
10.9.1 Digression:Making Screenshots 304
10.9.2 Printing an Image Fi le 305
10.9.3 Generating PDFs 306
10.9.4 TheTestApplication 306
10.10ComplexGraphics 307
10.10.1 Clipping 307
10.10.2 Painter Paths 309
10.10.3 Composition Modes 310
11 Input/OutputInterfaces 317
11.1The QIODeviceClass Hierarchy 317
11.1.1Derived Classes 318
11.1.2Opening I/O Devices 319
10
Contents
11.2Access to Local Files 320
11.3SerializingObjects 322
11.3.1Defining SerializationOperators 325
11.3.2SavingSerialized Data to aFile andReading from It 326
11.4Startingand ControllingProcesses 328
11.4.1SynchronousUse of QProcess 328
11.4.2AsynchronousUse of QProcess 330
11.5Communication in theNetwork 332
11.5.1NameResolutionwithQHostInfo 333
11.5.2Using QTcpServer andQTcpSocket 333
12 Threading with QThread337
12.1Using Threads 338

12.2SynchronizingThreads 341
12.2.1The Consumer/ProducerPattern. 342
12.3Thread-dependentDataStructures 345
12.4Using Signals andSlots Between Threads 347
12.5YourOwnEventLoops for Threads 350
12.5.1Communication via Events WithoutaThread-basedEvent
Loop 352
13 Handling XMLwithQtXml 353
13.1The SAX2 API. 354
13.1.1HowIt Works 354
13.1.2ReimplementingaDefault HandlertoReadRSS Feeds 355
13.1.3Digression:Equipping theRSS ReaderwithaGUI and
NetworkCapability 361
13.2The DOMAPI 366
13.2.1Reading in andProcessing XMLFiles 367
13.2.2Searching for SpecificElements 370
13.2.3Manipulatingthe DOMTree 371
13.2.4The DOMTreeasXML Output 372
11
Contents
14 Internationalization 375
14.1Translating Applications into Other Languages 375
14.1.1Preparing theApplication 376
14.1.2Processing Tr anslationSources withLinguist 377
14.1.3Using Translations in theProgram 378
14.1.4Adding Notesfor theTranslation 380
14.1.5Specifyingthe TranslationContext 380
14.1.6InternationalizingStrings OutsideQtClasses 381
Appendixes 383
ADebugging Help 385

A.1Debugging Functions 385
A.1.1SimpleDebug Output 386
A.1.2Errorsand Warnings 387
A.1.3Customizingthe Output of Debugging Functions 388
A.2WaystoEliminateErrors 390
A.2.1Checking Assertions 390
A.2.2Checking Pointers 391
A.2.3CommonLinkerErrors 392
BTulip: Containers andAlgorithms393
B.1Iterators 394
B.1.1STL-Style Iterators 395
B.1.2Java-Style Iterators. 396
B.2Lists 398
B.2.1SimpleList(QList) 400
B.2.2LinkedList(QLinkedList) 401
B.2.3Vectors (QVector) 401
B.3Stacks andQueues. 403
B.3.1Stacks (QStack) 403
B.3.2Queues(QQueue) 404
B.4AssociativeArrays 404
B.4.1Dictionaries (QMap) 404
12
Contents
B.4.2AllowingSeveral Identical Keys(QMultiMap) 407
B.4.3HashTableswithQHash 409
B.4.4Hash-basedAmountswithQSet. 411
B.5Algorithms 412
B.5.1The foreach Keyword 412
B.5.2Sorting 413
B.5.3Sorting in Unsorted Containers 414

B.5.4CopyingContainer Areas. 415
B.5.5BinarySearch in Sorted Containers 416
B.5.6Countingthe Number of Occurences of Equal Elements 418
B.5.7Deleting PointersinLists 418
B.5.8Checking that Data St ructures HaveIdentical Elements 419
B.5.9FillingDataStructures 420
B.5.10Swapping Values 420
B.5.11 Minimum, Maximum, andThreshold Values 421
B.5.12 DeterminingAbsoluteValue 422
B.6Qt-specificType Definitions 422
B.6.1Integer types 422
B.6.2Floating-point Values 423
B.6.3Shortcuts for CommonTypes 423
Index425
13

Foreword to the EnglishEdition
“Weneed an object-oriented displaysystem,” HaavardNordsaid, as thetwoofus
satonapark benchinthe summersun outsidethe regional hospital in Tr ondheim,
Norway,inthe summerof1991.
“Huh, what’sthat?”was myresponse.
Haavardwentontosketchwhatseemed likeanobvious idea at th etime. AC++
libraryof user interfacecomponents,orwidgets,thatwould havethe same APIon
allplatforms.
We hadbothjustgonethrough thetransitionfromprocedu ralprogramming to
event-driven programming andwereappalledatthe toolsavailable to do thejob.
Almost threeyears, acoupleofdesigniterations,and some serioushackinglater,we
incorporated whatwas to become Trolltech. At last wecould work full time on our
greatpassion:tomake thelives of programmers more pleasant.Weweresickand
tiredofusing toolsthatdetracted from thejoyof creating software. We wanted to

create toolsthatmade you th ink, “Ofcourse, this is thewayit was alwaysmeant
to be .”
And werefused to compromise.Wedesigned, redesigned,and threwawaylots of
code until wefeltwegot it just righ t. If ause casecould be solved byoneline
less of code andstill be easyto read ayearafter you hadwritten thecode (both
areimportant), then wewould ditchthe curr entdesignand redo whathad to be
redone.
TodayTrolltechhas almost 250employees andisapublic companylisted on the
Oslo stockexchange.But still, that passion for making thebestpossible developer
toolsare evidentinthe hallwaysofour offices.
Haavardand Ihaveleftthe controlofQt’sdestinyto muchmorecapable program-
mers than ourselves.And Ihavetosaytheyaredoing an extraordinaryjobatit. Qt
hasdevelopedintoanexceptionallybeautifulpiece of software.
TodayMatthiasEttrich(KDE founder)and Lars Knoll (ofKHTML fame) lead the
teamofdevelopers responsible for keepingQtthe kick-assproduct you expect
from Trolltech.
15
Foreword to theEnglish Edition
Qt 4ismoreorlessatotalrewrite of Qt. AndIknowoneofthe partsthe Trolltech
developers areespeciallyproudofisthe newpaintingengineinQt4.Itiscalled
Arthur the paint engine,after “Thomasthe Tank Engine,”
1
anditreallyis “the paint
engine that could!” Arthur hasdevelopedintoastate-of-the-artpaintingengine
that makesitpossible to easilycreate allthose eye-catchingvisual effectsend
usershavecometoexpect.And once you havecreated yourbreathtaking stuff,
recompilingwillmake it runonall platforms supported byQt.
From theveryfirst version of Qt released back in May1995, Trolltechhas been
usingadual-licensing business modelwithafree version of Qt available for devel-
opers of free andopensourcesoftware. Thefirsttoe in thewater back then was

abinary-onlyversi on for developmentoffreesoftwareunder Linuxonly.Thiswas
quicklyfollowed byafreeversion containing thecomplete source code.Today,Qt
is available both under astandardcommerciallicense andunder theGPL (General
Public License) on allplatforms.
What th is meansinpracticeisthatifyou wanttodonateyourworkbased on Qt
to thecommunityat largebylicensing yourworkunder theGPL,thengoahead
anduse ourproduct for free. Youcan even modifyandredistribute Qt under the
terms of theGPL,nostrings attached.If, on theother hand,you wan ttokeep
yoursoftwarebased on Qt proprietaryanddonot wanttolicense yourcode under
theGPL,thenyou also haveanoption. Youcan purchase Qt under astandard
commerciallicense from Trolltechand you can license yourcode anywayyou want,
no stringsattached.
Qt is an open source product withathrivingcommunityandatthe same time a
commercialproduct withthe backing of apublic companywithastrong developer,
support, anddocumentationmuscle. It reallyis thebestofbothworlds.
And it is because of thefeedback from thethousands of usersout there, both
commercialand opensourcedevelopers, that Qt is such ahigh-qualitytoolkit. We
still relyon andlisten closelyto allthe feedback wereceiveonQt. So,ifyou do find
somethingyou thinkcan be improved in Qt or simplyhaveabugtoreport, do not
hesitate to letusknow,e.g., bysendinganemail to We
haveateamofeagerengineerswanting to hear from you.
Well, Iguess Ihavebraggedenoughabout Qt now.The proof reallyis in thepud-
ding.The onlywayto trulyappreciate Qt is to startusing it.So, startdivinginto
this excellent coverage of Qt byDaniel Molkentin,and as you go along, playaround
withQtasmuchasyou can.Ido hope andbelievethatyou willbesurprised and
pleasedbytheprogramming universe of Qt.
Enjoy!
EirikChambe-Eng,
co-CEOand founder,TrolltechASA
1

See />16
Foreword to the GermanEdition
Traditionally,gettingapplications to look “justright”ondifferent operating systems
andplatforms hasbeen thestuff of nightmares for programmers. Applications on
Microsoft Windowslook andfeel different to thoseonMac OS X, which in turn
aredifferent for thoseusing Linuxplatforms.Applications written for Linuxeven
behavedifferentlyon thevarious free desktopenvironmentsavailable,and much
thesamecan be said of thevarious flavorsofWindows.
While it is relativelyeasyto write code that works on allofthese platforms,such
code is either likelyto feel alienonall butthe oneplatformitwas originallyde-
signed for,oritdoesn’t providefeaturesthatusers expect to findinmodern appli-
cations.
With Qt, ouraimsare muchhigherthanthis. We wantapplications written with
Qt to be written in aplatform-independentway,yet workaswellasanyother
applicationonMicrosoft Windows, MacOSX,and Linuxdesktops—even on mobile
devices.Writing code to make this possi ble is no easytask;itisone that providesa
new—and welcome—challengefor theTrolltechteamofdevelopers each day.
ThemostdifficultpartofQttoget right, andalsothe most visible, is thegraphical
user interface(GUI). Thefoundationfor anyGUI is thetechnologyused to ren-
derthe interface, andQtcontainsits owntechnologyfor this purpose—namely
“Arthur thePaint Engine.” Partlyinspired by“Thomasthe Tank Engine,” Arthur has
come alongwayin recent years. Itsstoryis agood exampleofhowQt hascontin-
uedtodevelop as usersprovidefeedback andsuggest solutionstoproblems they
encounter.
Arthur began withjustsuchasimple problem: ManyQt usersmake useofOpenGL
in theirsoftware, andtheyincreasinglywanted to be able to choosebetween draw-
ingwithOpenGLand drawingonconventional widgets,but usethe same applica-
tion programming interface(API) for both.Wewanted to providethisabilitywith
Qt 4. Easier said than done!The oldpaint devicearchitecture,nearly10years old
whenwestarted,could notcope withthischange, andsoalittlerefactoringwas

necessarybeforeArthur couldsee thelight of day.Inthe first TechnologyPreview
of Qt 4, wewereable to drawgraphicsnot onlywithOpenGL, butalsoonthe
relativelynewGDI+ on Windows, withbothanti-aliasing andlineargradients.
17
Foreword to theGermanEdition
Verynice,wethought,and far better than Qt 3, butwehad failedtoreckonwith
thehighexpectationsofour users. Manychangeshad been taking placeinthe
world of computer graphics. TheXRender extension to X11was becoming ever
more powerful, theCairo projectwas getting readyto closethe gap withother
systemsonceand for all, theMacintoshhad CoreGraphics, andanewScalable
Vector Graphics(SVG) formathad beguntoindicatewhere modern toolkits were
going at thebeginning of the21stcentury.
Arthur was on theright path, butwestill hadanenormousamount of ground to
make up.Thingsthatworkedfastonthe MacwereslowwithGDI+onWindows
or wit hX11, andviceversa.And under X11—ourcoreplatformfor theopensource
version—wewerealong waybe hind,even whenusing extensionslikeXRender.
Team Arthur,headedbyGunnarSletta,thereforeset itself anewgoal:tomatch the
featureset offeredbySVG. Theteamwas determinednot to rest until high-quality
vectorgraphicscould be displayed equallywellonall platforms,and at high speed,
too. Allthishappened,mindyou, after therelease of thefirstQt4Technology
Preview.
Howwou ld you havereacted as theproject manager? We knewthat oursolution
was notgood en ough,but wewerealreadybehind schedule.And howcan you
putyourfaith in twodevelopers alonebeing able to write anewrenderer that
willcompete withthe giants of operating system vendors? Notonlythis,wealso
wanted it to be even better than GDI+,and platformindependent as well. Team
Arthur was given threeweekstobuild aprototype to showwhatitcould achieve.
Thetwoofthemcameupwiththe goods!The breakthrough success was due
to thefantastic scan-lineconverter from theFreeType project, apiece of open
source softwarethatisgenerallyused to displaytext. It took just threemoredays

to displaycomplexSVGs withfloating-point precision, anti-aliasing,and powerful
gradients.
What can welearn from this?Qtiscontinuallybeingdevelopedbyhighlymoti-
vated (and sometimesquite crazy)programmers whocallthemselves Trolls,who are
spurredontoprovidethe best product for ourusers. It is also developedbyded-
icated peoplelikeDanieland Patricia,towhomour thanks go forproducing this
wonderful book you areholding in yourhands,and bymanyothercontributors
andusers around theworld.
Withoutthispriceless community,Qtwould notbewhere it is today,and thede-
velopmentteamisgratefullyawareofthis. This is preciselythereasonwewill
continue to strivefor more andbetter.For you,our users—andbecause weenjoyit
alittlebit,ofcourse. WelcometoQt!
MatthiasEttrich,
Head of Development, Trolltech
18
Introduction
Anumber of years ago,Ihappenedtocomeacrossanarticle on GUI programming
withC++. Ihad just started learning C++and was amazed at howlittlecode the
author
2
needed to produce acomplete game, includingthe menus.Ofcourse, there
wereanumber of constructs that needed explanation, butafter ashort time Iwas
hooked:The Qt librarythat he used turned ou tnot onlyto haveaveryextensive
collectionofall kindsofuseful widgets (alsoknowntoWindowsprogrammers as
controlelements ), butinaddition hadstandardalgorithms,datastructures, and
othernongraphic classesthatmade programming withC++ so intuitive, in away
that Ihad never seen beforeinanyothertoolkit.
Thesoftwarecompany,Trolltech, was also promotingits ownplatform-independent
API. This toolkit, which couldproduce programsfor bo th Windowsand Linux,sim-
plybyrecompilingthe code,attracted myattention.Shortlyafter this,nearlysix

years ago to theday,Ijoined theKDE project, which was developing an entire desk-
topbased on Qt. Today,together withGNOME, KDE is oneofthe most important
desktops under Linux.But Qt is also used byasubstantial number of companies:
GoogleEarth is basedonQt, as is thetelephonysoftwareSkype andthe video
editingprogram MainActor.
When Tr olltechpublishedapre-version of Qt 4in2005, Istarted tryingout several
of thenewfunctionalitiesand was veryimpressed. Forthe first time therewas
auniformlicensing scheme for variationsofQt, which until th en weredifferent
for LinuxandMac OS X: Quid proquo—those companiesthatpublishaprogram
under an open source licen se mayusethe opensourceversion of thelibrary.But
if thecompanyis developing proprietaryprograms, then it paysfor Qt license fees,
thus supporting thedevelopmentofthe toolkit, andreceives supportfromthe
manufacturer.
This structural level is of relevance as far as thelicensing of th ecommercialQt
version.Trolltechhas th reeeditionsofQt4available: Qt Console for nongraphic
development, and Qt Desktop Light and Qt Desktop as versionscontainingall
features.The opensourceversion in each casecorresponds to thedesktop edition,
so it is notrestricted in anywayin terms of size.
2
Thearticle was writtenbyMatthiasEttrich, thefounder of theKDE project.
19
Introduction
This book is basedonthe opensourceedition of Qt, butitcan also be used without
problembythosewho havepurchased thecommercialversion.The embedded
version of Qt ( QtopiaCore )isnot covered in thebook,because although theAPI
is identical,apart from afewextraclasses, th ereare so manyitemstobenoted in
embeddeddevelopmentthataseparatebook would be needed to describe them
all.
Target Audienceand Prerequisites
It is difficulttodefine atargetaudiencefor Qt programming because theareas of

applicationfor Qt arealmostlimitless.Ingeneral,however,itisaimed at allthose
who wishtohaveplatform-independentresults in amachine-oriented high-level
language such as C++, resultsthatcan be compiledintonativecode,not le astfor
reasonsofperformance.
Thebook assumesthatyou haveafundamentalknowledge of C++. An interested
readershouldbefamiliarwiththe concepts of pointersand templates.The book
also assumesthatyou knowaboutthingssuchasthe overloading of operators.
Knowledge of theStandardTemplateLibrary(STL) in particular is notexpected.Qt
provides itsownclassesfor themostcommonalgorithms andcontainers, which
areexplainedinAppendixB.
Structur eofthe Book
Thebook first explains thebasic structureofthe Qt toolkit, together wit hits most
important specificproperties. Thesubsequentchaptersconcentrate on writing your
ownsmall applications.All othertechnologies,presented in thefinalchapters, are
demonstrated as short, independentexamples for thesake of clarity.But theyare
arranged in such awaythat it should be no problemtouse them in arealprogram
at thecorrect position.
Nearlyallofthe examples printed in this book arebased on acomplete andcompi-
lable testprogram.These examples beginwiththe name of th equoted source text
fileinC++ comments, such as
// program_name/file_name.cpp
Forabetter understanding,explanations areoften added between code segments,
so that thecode is interrupted.Whenthe code continuesinsuchcases,itisalso
marked as acomment:
// program_name/file_name.cpp (continued)
20
Introduction
If you prefer to read theexamples in context, or wanttotrythem outyou rself, you
can download acomplete archivewithall theexamples describedinthe book.This
file, as wellasother hintsand lin krecommendations,isavailable at thewebsite for

thebook:
/>This book is aimedatbeginners andisnot intendedtobeareference. Theexcel-
lent onlinedocumentation—which can be calledvia theQtAssistantincorporated
in thedistribution or onlineat adetailedAPI
documentationonall theclassesintroducedhere, andwould be hard to beat.
Instead, thebook aims to explaincontexts andbasic techniques bytheuse of
examples,and to simplifygetting started withprogramming,justasthatmagazine
articleback th en helped me whenIwas starting to gettogrips withQt.
Note of Thanks
It would havebeen impossible to read th is book without anumber of peoplegiving
me supportwiththeir advice.Inparticular, Patricia Jung andher colleagues from
Open Source Pressmade asignificantcontribution as farasthe formand contents
of th ebook wereconcerned.Further thanks go to Rainer M. Schmid, who also
helped in getting theproject off theground,and SteveTomlin,who didafantastic
jobintranslating this book.
Iwould also liketothank thepeoplewho proofreadthe book,providingmewith
valuable feedback. Thorsten St
¨
arkand StephanZeissler deservespecial mention
here,aswellasAxel J
¨
ager, withwhomIhadmanyvaluable discussions.
Iwould never havewritten this book,ofcourse, if Ihad notbumped into the
KDE projectand metHarri Porten,apatient maintainer who looked after myfirst
patches andcommented on them withgreat patience.
As the book was beingwritten,Ialso found supportfromthe extremelyhelpful
membersofthe #kde4-devel channelatirc.freenode.net who provided important
tips andadvice. ThemailinglistarchiveofTrolltechand thecommunityforum
also provided valuable tips,clarifyingsometrickyques-
tions.

Trolltechitselfdeserves specialthanks, because duetothe dual licensing,the com-
panysupports theidealsoffreesoftware. In some cases thesourcetextwas the
last possibilityof confirmingcertain technical issues,where gaps weretobeeven
in theexcellent APIdocumentation.
TheLinux/UnixUsergroup SanktAugustinand theBonnerNetzladenalsodeserve
aspecial mention. Theirexcellent provisionofClub-Mate iced tea alwayskeptme
wideawake during mywork.
21
Introduction
Manyof myfriendshavegiven me encouragement andmot ivationonthisproject,
andmanythanks should also go to myfamily.Theyprovided support, particularly
in thecritical phases,which was agreat help in mywork. This book is therefore
dedicatedtothe best familyIcould askfor.
Daniel Molkentin
22
Preparations
Youshouldalwaysuse themostrecen tQtversion from Trolltech
3
to en sure hav-
ingasmanybugfixes covered as possible.Linuxusersmayalso usethe precom-
piledpackagesfromtheir Linuxdistribution,but theyshould be prepared to meet
some—often subtle—problems witholder distributionslikeUbuntuDapper Drake,
where problems withthe debuglibrarieshavebeen reported.Inthese cases,itis
safertoobtainthe source texts from Tr olltech, andcompile thesources yourselfas
describedbelow.
On OS X, you can choosebetween compilingQtyourselforusing adiskimage (.dmg)
archive, which installs precompiledlibrariesto/opt/qt 4. Thelatter willinstall only
thestaticlibraries, which areeasilyidentifiedvia theirextension (.a).Atlinktime,
theselibrariesbecomepartofthe binary.Asecond .dmg archivecontainsthe debug
version of allQtlibraries, which should be installedondevelopmentsystems, too.

AlthoughQtcan be configuredtobuild static librariesonall platforms,thisis
mostlyused on Mac OS X, where static linking is thepreferred wayto avoidli-
braryproblems,atthe expenseofdiskspace.
If you choosetobuild thesources on Linuxor Mac OS X, it is sufficienttounpack
thearchive, and—providedyou haveacompilerinstalled—runthe command
./configure-qt-gif -debug
make
from withinthe packagedirectory.Beforehandyou should check, using./configure
-help, whether th esystem takesaccount of specificmodulesduringcompilation,
such as particular databasedrivers, which you mayrequirefor yourwork. More
detailednotes,especiallyon theSQL modules, areavailable in thecorresponding
chaptersofthisbook.
Theparametersspecifiedherefor configure haveturnedout to be thesmallest
commondenominator formanyapplicationcases:-qt-gif addssupportfor theGIF
fileformat, disabledbydefaultfor reasonsoflicensing,tobeincludedinthe library.
-debug ensuresthataversion withdebugging iconsisbuilt,apart from thenormal
3
See />23

×