C++ GUI Programming with Qt 4 C++ GUI Programming with Qt 4 JasminBlanchette MarkSummerfield InassociationwithTrolltechPress UpperSaddleRiver,NJ·Boston·Indianapolis·SanFrancisco NewYork·Toronto·Montreal·London·Munich·Paris·Madrid Capetown·Sydney·Tokyo·Singapore·MexicoCity Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedas trademarks. Wherethosedesignationsappearinthisbook,andthepublisherwasawareofatrademark claim,thedesignationshavebeenprintedwithinitialcapitallettersorinallcapitals. Theauthorsand publisherhavetaken carein the preparationof thisbook,but makenoexpressedor impliedwarrantyofanykindandassumenoresponsibilityforerrorsoromissions. Noliabilityisassumed forincidentalorconsequentialdamagesinconnectionwithorarisingoutoftheuseoftheinformationor programscontainedherein. Thepublisheroffersexcellent discountson thisbook whenorderedin quantityforbulk purchasesor specialsales,whichmayincludeelectronicversionsand/orcustomcoversandcontentparticulartoyour business,traininggoals,marketingfocus,andbrandinginterests. Formoreinformation,pleasecontact: U.S.CorporateandGovernmentSales (800)382-3419 [email protected] ForsalesoutsidetheUnitedStates,pleasecontact: InternationalSales [email protected] VisitusontheWeb: www.prenhallprofessional.com ThisBookIsSafariEnabled TheSafariEnabledicononthecoverofyourfavoritetechnologybookmeansthebook isavailablethroughSafariBookshelf. Whenyoubuythisbook,yougetfreeaccessto theonlineeditionfor45days. SafariBookshelfisanelectronicreferencelibrarythatletsyoueasilysearchthousandsoftechnicalbooks, find code samples,download chapters,and accesstechnical information whenever and whereveryou needit. Togain45-daySafariEnabledaccesstothisbook: • Gotohttp://www.prenhallprofessional.com/safarienabled • Completethebriefregistrationform • EnterthecouponcodeFTMP-7EXM-TI8P-6GM1-3Y85 IfyouhavedifficultyregisteringonSafariBookshelforaccessingtheonlineedition,pleasee-mail [email protected]. Libraryof CongressCataloging-in-PublicationData Blanchette,Jasmin. C++GUIprogrammingwithQt4/JasminBlanchette,MarkSummerfield. p. cm. Includesbibliographicalreferencesandindex. ISBN0-13-187249-4(pbk.:alk. paper) 1.Graphicaluserinterfaces(Computersystems)2.C++(Computerprogramlanguage) I.Summerfield,Mark. II.Title. QA76.9.U83B5322006 005.4’37—dc22 2006013376 Copyright©2006TrolltechAS Allrightsreserved. PrintedintheUnitedStatesof America. Thispublicationmayonlybedistributed subjecttothetermsand conditionsset forthintheOpenPublicationLicense,v1.0orlater(thelatest versionisavailableathttp://www.open-content.org/openpub/). Trolltech,Qt,Qtopia,andtheTrolltechandQtopialogosareregisteredtrademarksofTrolltechAS. ISBN0-13-187249-4 TextprintedintheUnitedStatesonrecycledpaperatCourierinStoughton,Massachusetts. Firstprinting,June2006 Contents Foreword ......................................................... ix Preface ........................................................... xi Acknowledgments ................................................ xiii ABrief Historyof Qt ............................................. xv PartI: Basic Qt 1. GettingStarted ................................................ 3 HelloQt ..................................................... 3 MakingConnections ......................................... 5 LayingOutWidgets .......................................... 6 UsingtheReferenceDocumentation .......................... 9 2. CreatingDialogs............................................... 13 SubclassingQDialog ......................................... 13 SignalsandSlotsinDepth .................................... 20 RapidDialogDesign ......................................... 23 Shape-ChangingDialogs ..................................... 29 DynamicDialogs ............................................. 36 Built-inWidgetandDialogClasses ........................... 37 3. CreatingMainWindows ....................................... 43 SubclassingQMainWindow................................... 44 CreatingMenusandToolbars ................................. 48 SettingUptheStatusBar .................................... 52 ImplementingtheFileMenu.................................. 54 UsingDialogs ................................................ 61 StoringSettings.............................................. 67 MultipleDocuments.......................................... 68 SplashScreens ............................................... 71 v 4. ImplementingApplicationFunctionality ..................... 73 TheCentralWidget .......................................... 73 SubclassingQTableWidget ................................... 74 LoadingandSaving .......................................... 80 ImplementingtheEditMenu ................................. 83 ImplementingtheOtherMenus............................... 87 SubclassingQTableWidgetItem ............................... 91 5. CreatingCustomWidgets ..................................... 101 CustomizingQtWidgets ...................................... 101 SubclassingQWidget ......................................... 103 IntegratingCustomWidgetswithQtDesigner ................. 113 DoubleBuffering ............................................. 116 PartII: Intermediate Qt 6. LayoutManagement........................................... 137 LayingOutWidgetsonaForm ................................ 137 StackedLayouts ............................................. 143 Splitters ..................................................... 145 ScrollingAreas............................................... 148 DockWidgetsandToolbars ................................... 150 MultipleDocumentInterface ................................. 152 7. EventProcessing .............................................. 163 ReimplementingEventHandlers ............................. 163 InstallingEventFilters....................................... 168 StayingResponsiveDuringIntensiveProcessing .............. 171 8. 2Dand3DGraphics ........................................... 175 PaintingwithQPainter....................................... 175 PainterTransformations ..................................... 180 High-QualityRenderingwithQImage......................... 188 Printing ..................................................... 190 GraphicswithOpenGL ....................................... 198 9. DragandDrop ................................................. 205 EnablingDragandDrop ..................................... 205 SupportingCustomDragTypes ............................... 210 ClipboardHandling .......................................... 215 vi 10. ItemViewClasses ............................................ 217 UsingtheItemViewConvenienceClasses ..................... 218 UsingPredefinedModels ..................................... 225 ImplementingCustomModels ................................ 230 ImplementingCustomDelegates.............................. 244 11. ContainerClasses ............................................ 251 SequentialContainers........................................ 252 AssociativeContainers ....................................... 260 GenericAlgorithms .......................................... 263 Strings,ByteArrays,andVariants ............................ 265 12. Input/Output ................................................. 273 ReadingandWritingBinaryData ............................ 274 ReadingandWritingText .................................... 279 TraversingDirectories........................................ 285 EmbeddingResources ........................................ 286 Inter-ProcessCommunication................................. 287 13. Databases..................................................... 293 ConnectingandQuerying .................................... 294 PresentingDatainTabularForm ............................. 299 ImplementingMaster–DetailForms .......................... 304 14. Networking ................................................... 311 WritingFTPClients.......................................... 311 WritingHTTPClients ........................................ 320 WritingTCPClient–ServerApplications ...................... 323 SendingandReceivingUDPDatagrams....................... 333 15. XML ........................................................... 339 ReadingXMLwithSAX ...................................... 339 ReadingXMLwithDOM ..................................... 344 WritingXML ................................................ 348 16. ProvidingOnlineHelp ....................................... 351 Tooltips,StatusTips,and“What’sThis?”Help ................. 351 UsingQTextBrowserasaSimpleHelpEngine ................. 353 UsingQtAssistantforPowerfulOnlineHelp .................. 356 vii PartIII: Advanced Qt 17. Internationalization ......................................... 361 WorkingwithUnicode ........................................ 362 MakingApplicationsTranslation-Aware ...................... 365 DynamicLanguageSwitching ................................ 371 TranslatingApplications ..................................... 376 18. Multithreading ............................................... 381 CreatingThreads ............................................ 381 SynchronizingThreads ....................................... 385 CommunicatingwiththeMainThread ........................ 391 UsingQt’sClassesinSecondaryThreads ...................... 396 19. CreatingPlugins ............................................. 399 ExtendingQtwithPlugins ................................... 400 MakingApplicationsPlugin-Aware ........................... 408 WritingApplicationPlugins .................................. 412 20. Platform-SpecificFeatures ................................... 415 InterfacingwithNativeAPIs ................................. 415 UsingActiveXonWindows ................................... 419 HandlingX11SessionManagement ........................... 431 21. EmbeddedProgramming..................................... 439 GettingStartedwithQtopia .................................. 440 CustomizingQtopiaCore ..................................... 441 Appendices A. Installing Qt ................................................... 447 B. IntroductiontoC++forJavaandC#Programmers .......... 451 Index ............................................................. 493 viii Foreword WhyQt? WhydoprogrammerslikeuschooseQt? Sure,therearetheobvious answers:Qt’ssingle-source compatibility,itsfeature richness,itsC++perfor- mance,theavailabilityof thesourcecode,itsdocumentation,thehigh-quality technicalsupport,andalltheotheritemsmentionedinTrolltech’sglossymar- ketingmaterials. Thisisallverywell,butitmissesthemostimportantpoint: Qtissuccessfulbecauseprogrammerslikeit. Howcomeprogrammerslikeonetechnology,butdislikeanother? PersonallyI believesoftwareengineersenjoytechnologythatfeelsright,butdislikeevery- thingthatdoesn’t. “Feelsright”meansmanythings. IntheQt3editionof the book,ImentionedTrolltech’sphonesystemasaparticularlygoodexampleof someparticularlybadtechnology. Thephonesystemdidn’tfeelright,because itforcedustodoapparentlyrandomthingsdependingonsomeequallyrandom context. Randomnessdoesn’tfeelright. Anotherthingthatdoesn’tfeelright isrepetitivenessandredundancy. Goodprogrammersarelazy. Whatwelove about computerscompared to,say,gardening is that we don’t have to do the samethingsoverandover. Letmeemphasizethispointwithareal-worldexample:travelreimbursement forms. Typically those forms come as fancy spreadsheets;you fill them out, and you get real money. Simple technology,one should think,and given the monetaryincentivethisshouldbeasimpletaskforagrown-upengineer. Reality looks different,though. While nobody else in the company seems to haveanyproblemswhatsoeverdealingwiththoseforms,theengineersdo. And havingtalkedtopeopleinothercompanies,thisseemstobeacommonpattern. Wedeferreimbursementuntiltheverylastmoment,andsometimeswemight evenforgetaboutit. Whyisthat? Lookingatourform,it’sastraightforward, standardprocedure. Onehastocollectreceipts,numberthem,andputthose numbersinto theproper fieldswith thedate,thelocation,a description,and theamount. Thenumberingandcopyingisdesignedtoeasesomeone’swork, butstrictlyspeakingitisredundant,giventhatthedate,location,description, andamountunambiguouslyidentifyareceipt. Atinybitof extraworktoget yourmoneyback,onewouldthink. A smallannoyanceistheper-diemrate,though,whichdependsonthetravel location. There’ssomeseparatedocumentsomewherethatliststhestandard- izedratesforallthedifferenttravellocations. Youcan’tjustselect“Chicago”; instead you have to look up the rate for Chicago yourself. There’s a similar annoyancewiththeexchangeratefield. Onehastofindthecurrentexchange ratesomewhere—perhapswithGoogle’shelp—andthenentertherateinev- ix ery single field. Well,strictly speaking,you should wait for your credit card companytoissueastatementtoyouwiththeactualexchangeratethatthey used. Whilethisisnot hardtodo,looking updifferentpiecesof information fromdifferentsources,and then copying therelevant itemstoseveralplaces intheformfeelsneedlesslyawkward. Programming can be a lot like filling in travel reimbursement forms, only worse. AndthisiswhereQtcomestotherescue. Qtisdifferent. Foronething, Qt makessense. And for another,Qt isfun. Qt letsyou concentrateon your tasks. WhenQt’soriginalarchitectsfacedaproblem,theydidn’tjustlookfor a good solution,or the simplest solution. They looked for the right solution, andthentheydocumentedit. Grantedtheymademistakes,andgrantedsome of theirdesigndecisionsdidn’tpassthetestof time,buttheystillgotalotof thingsright,and what wasn’t right could and can be corrected. You can see thisby the fact that a system originally designed to bridge Windows95 and Unix/Motif now unifies modern desktop systems as diverse as Windows XP, MacOSX,andGNU/Linux,andprovidesthefoundationfortheQtopiaappli- cationplatformforembeddedLinux. Long beforeQt becameso popular and sowidely used,thededicationof Qt’s developerstofinding theright solutionsmadeQt special. That dedicationis justasstrongtodayandaffectseveryonewhodevelopsandmaintainsQt. For us,workingonQtisaresponsibilityandaprivilege. Weareproudof helping tomakeyourprofessionalandopensourceliveseasierandmoreenjoyable. MatthiasEttrich Oslo,Norway June2006 x