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