Table Of ContentC++ GUI Programming
with Qt 4
Second Edition
This page intentionally left blank
C++ GUI Programming
with Qt 4
Second Edition
JasminBlanchette
MarkSummerfield
InassociationwithTrolltechPress
UpperSaddleRiver,NJ·Boston·Indianapolis·SanFrancisco
NewYork·Toronto·Montreal·London·Munich·Paris·Madrid
Capetown·Sydney·Tokyo·Singapore·MexicoCity
Manyof thedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedas
trademarks. Wherethosedesignationsappearinthisbook,andthepublisherwasawareof atrademark
claim,thedesignationshavebeenprintedwithinitialcapitallettersorinallcapitals.
Theauthorsandpublisherhavetakencareinthepreparationofthisbook,butmakenoexpressedorimplied
warrantyof anykindandassumenoresponsibilityforerrorsoromissions. Noliabilityisassumedfor
incidentalorconsequentialdamagesinconnectionwithorarisingout of theuseof theinformationor
programscontainedherein.
Thepublisheroffersexcellentdiscountsonthisbookwhenorderedinquantityforbulkpurchasesorspecial
sales,whichmayincludeelectronicversionsand/orcustomcoversandcontentparticulartoyourbusiness,
traininggoals,marketingfocus,andbrandinginterests. Formoreinformation,pleasecontact:
U.S.CorporateandGovernmentSales
(800)382-3419
[email protected]
ForsalesoutsidetheUnitedStates,pleasecontact:
InternationalSales
[email protected]
VisitusontheWeb:www.prenhallprofessional.com
ThisBookIsSafariEnabled
TheSafari®Enabledicononthecoverofyourfavoritetechnologybookmeansthebook
isavailablethroughSafariBookshelf. Whenyoubuythisbook,yougetfreeaccesstothe
onlineeditionfor45days.
SafariBookshelfisanelectronicreferencelibrarythatletsyoueasilysearchthousandsoftechnicalbooks,
find code samples, download chapters, and access technical information whenever and wherever you
needit.
Togain45-daySafariEnabledaccesstothisbook:
• Gotohttp://www.prenhallprofessional.com/safarienabled
• Completethebriefregistrationform
• EnterthecouponcodeS1F3-5NDG-9Z64-LNGX-K8F2
IfyouhavedifficultyregisteringonSafariBookshelforaccessingtheonlineedition,pleasee-mail
[email protected].
Libraryof CongressCataloging-in-PublicationData
Blanchette,Jasmin.
C++GUIprogrammingwithQt4/JasminBlanchette,MarkSummerfield.–2nded.
p. cm.
Includesindex.
ISBN-13:978-0-13-235416-5 (hardcover:alk. paper)
1.Qt(Electronicresource) 2.Graphicaluserinterfaces(Computersystems) 3.C++(Computerprogram
language) I.Summerfield,Mark. II.Title.
QA76.9.U83B5322008
005.13’3—dc22
2008000243
Copyright©2008TrolltechASA
Allrightsreserved. PrintedintheUnitedStatesof America. Thispublicationmayonlybedistributed
subjecttothetermsandconditionssetforthintheOpenPublicationLicense,v1.0orlater(thelatestversion
isavailableathttp://www.opencontent.org/openpub/).
Trolltech®,Qt®,Qtopia®,andtheTrolltechandQtopialogosareregisteredtrademarksofTrolltechASA.
ISBN-13:978-0-13-235416-5
ISBN-10: 0-13-235416-0
TextprintedintheUnitedStatesonrecycledpaperatCourierinWestford,Massachusetts.
Firstprinting,February2008
Contents
SeriesEditor’sNote ............................................... xi
Foreword .......................................................... xiii
Preface ............................................................ xv
Acknowledgments ................................................. xvii
ABrief Historyof Qt .............................................. xix
PartI: Basic Qt
1. GettingStarted ................................................. 3
HelloQt ...................................................... 3
MakingConnections........................................... 5
LayingOutWidgets ........................................... 6
UsingtheReferenceDocumentation ........................... 10
2. CreatingDialogs ................................................ 13
SubclassingQDialog .......................................... 13
SignalsandSlotsinDepth ..................................... 20
RapidDialogDesign........................................... 23
Shape-ChangingDialogs ...................................... 31
DynamicDialogs .............................................. 38
Built-inWidgetandDialogClasses............................. 39
3. CreatingMainWindows ........................................ 45
SubclassingQMainWindow .................................... 46
CreatingMenusandToolbars .................................. 50
SettingUptheStatusBar ..................................... 55
ImplementingtheFileMenu................................... 57
UsingDialogs ................................................. 63
StoringSettings............................................... 69
MultipleDocuments ........................................... 71
SplashScreens ................................................ 74
v
4. ImplementingApplicationFunctionality ...................... 77
TheCentralWidget ........................................... 77
SubclassingQTableWidget .................................... 78
LoadingandSaving ........................................... 84
ImplementingtheEditMenu .................................. 87
ImplementingtheOtherMenus................................ 91
SubclassingQTableWidgetItem ................................ 95
5. CreatingCustomWidgets ...................................... 105
CustomizingQtWidgets ....................................... 105
SubclassingQWidget .......................................... 107
IntegratingCustomWidgetswithQtDesigner .................. 117
DoubleBuffering .............................................. 121
PartII: Intermediate Qt
6. LayoutManagement............................................ 141
LayingOutWidgetsonaForm ................................. 141
StackedLayouts .............................................. 147
Splitters ...................................................... 149
ScrollingAreas................................................ 152
DockWindowsandToolbars ................................... 154
MultipleDocumentInterface .................................. 157
7. EventProcessing ............................................... 167
ReimplementingEventHandlers .............................. 167
InstallingEventFilters........................................ 172
StayingResponsiveduringIntensiveProcessing ................ 175
8. 2DGraphics..................................................... 179
PaintingwithQPainter ........................................ 180
CoordinateSystemTransformations ........................... 185
High-QualityRenderingwithQImage .......................... 193
Item-BasedRenderingwithGraphicsView ..................... 195
Printing ...................................................... 217
9. DragandDrop .................................................. 227
EnablingDragandDrop....................................... 227
SupportingCustomDragTypes ................................ 232
ClipboardHandling ........................................... 237
vi
10. ItemViewClasses ............................................. 239
UsingtheItemViewConvenienceClasses ...................... 240
UsingPredefinedModels ...................................... 247
ImplementingCustomModels ................................. 252
ImplementingCustomDelegates............................... 266
11. ContainerClasses ............................................. 273
SequentialContainers ......................................... 274
AssociativeContainers ........................................ 282
GenericAlgorithms............................................ 285
Strings,ByteArrays,andVariants ............................. 287
12. Input/Output .................................................. 295
ReadingandWritingBinaryData ............................. 296
ReadingandWritingText ..................................... 301
TraversingDirectories......................................... 307
EmbeddingResources ......................................... 308
Inter-ProcessCommunication .................................. 309
13. Databases ...................................................... 315
ConnectingandQuerying ..................................... 316
ViewingTables................................................ 322
EditingRecordsUsingForms .................................. 324
PresentingDatainTabularForms ............................. 330
14. Multithreading ................................................ 339
CreatingThreads ............................................. 340
SynchronizingThreads ........................................ 343
CommunicatingwiththeMainThread ......................... 349
UsingQt’sClassesinSecondaryThreads ....................... 356
15. Networking .................................................... 359
WritingFTPClients........................................... 359
WritingHTTPClients ......................................... 368
WritingTCPClient–ServerApplications ....................... 371
SendingandReceivingUDPDatagrams........................ 381
16. XML ............................................................ 387
ReadingXMLwithQXmlStreamReader ........................ 388
ReadingXMLwithDOM ...................................... 395
vii
ReadingXMLwithSAX ....................................... 400
WritingXML ................................................. 404
17. ProvidingOnlineHelp ........................................ 407
Tooltips,StatusTips,and“What’sThis?”Help .................. 407
UsingaWebBrowsertoProvideOnlineHelp ................... 409
UsingQTextBrowserasaSimpleHelpEngine .................. 411
UsingQtAssistantforPowerfulOnlineHelp ................... 414
PartIII: Advanced Qt
18. Internationalization........................................... 419
WorkingwithUnicode ......................................... 420
MakingApplicationsTranslation-Aware ....................... 423
DynamicLanguageSwitching ................................. 429
TranslatingApplications ...................................... 435
19. LookandFeelCustomization ................................. 439
UsingQtStyleSheets ......................................... 439
SubclassingQStyle ............................................ 454
20. 3DGraphics ................................................... 471
DrawingUsingOpenGL ....................................... 471
CombiningOpenGLandQPainter ............................. 477
DoingOverlaysUsingFramebufferObjects ..................... 484
21. CreatingPlugins .............................................. 491
ExtendingQtwithPlugins .................................... 492
MakingApplicationsPlugin-Aware ............................ 502
WritingApplicationPlugins ................................... 505
22. ApplicationScripting ......................................... 509
Overviewof theECMAScriptLanguage ........................ 510
ExtendingQtApplicationswithScripts ........................ 519
ImplementingGUIExtensionsUsingScripts ................... 523
AutomatingTasksthroughScripting ........................... 530
23. Platform-SpecificFeatures .................................... 543
InterfacingwithNativeAPIs .................................. 543
UsingActiveXonWindows .................................... 547
HandlingX11SessionManagement ............................ 559
viii
24. EmbeddedProgramming ..................................... 567
GettingStartedwithQt/EmbeddedLinux ...................... 568
CustomizingQt/EmbeddedLinux .............................. 570
IntegratingQtApplicationswithQtopia ........................ 571
UsingQtopiaAPIs ............................................ 576
Appendixes
A. Obtaining and Installing Qt ................................... 589
B. BuildingQtApplications ...................................... 593
C. IntroductiontoQtJambi ...................................... 605
D. IntroductiontoC++forJavaandC#Programmers ........... 623
Index .............................................................. 665
ix