Tải bản đầy đủ (.pdf) (1,005 trang)

C++ GUI programming with qt 4 (2006)

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 (8.34 MB, 1,005 trang )

C++GUIProgrammingwithQt4
ByJasminBlanchette,MarkSummerfield
...............................................
Publisher:PrenticeHall
PubDate:June21,2006
PrintISBN-10:0-13-187249-4
PrintISBN-13:978-0-13-187249-3
Pages:560

TableofContents|Index

TheOnlyOfficialBest-PracticeGuidetoQt4.1Programming
UsingTrolltech'sQtyoucanbuildindustrial-strengthC++applicationsthatrunnativelyon
Windows,Linux/Unix,MacOSX,andembeddedLinux--withoutmakingsourcecode
changes.WiththisbookTrolltechinsidershavewrittenastart-to-finishguidetogetting
greatresultswiththemostpowerfulversionofQtevercreated:Qt4.1.
UsingC++GUIProgrammingwithQt4you'lldiscoverthemosteffectiveQt4
programmingpatternsandtechniquesasyoumasterkeytechnologiesrangingfromQt's
model/viewarchitecturetoQt'spowerfulnew2Dpaintengine.Theauthorsprovide
readerswithunparalleledinsightintoQt'seventmodelandlayoutsystem.Then,using
realisticexamples,theyintroducesuperiortechniquesforeverythingfrombasicGUI
developmenttoadvanceddatabaseandXMLintegration.
IncludesnewchaptersonQt4'smodel/viewarchitectureandQt'snewplugin
support,alongwithabriefintroductiontoQtopiaembeddedprogramming
CoversallQtfundamentals,fromdialogsandwindowstoimplementingapplication
functionality
Introducesbestpracticesforlayoutmanagementandeventprocessing
ShowshowtomakethemostofQt4'snewAPIs,includingthepowerfulnew2D
paintengineandtheneweasy-to-usecontainerclasses
Containscompletelyupdatedmaterialineverychapter
PresentsadvancedQt4techniquescoveredinnootherbook,fromcreatingbothQt


andapplicationpluginstointerfacingwithnativeAPIs
Containsanin-depthappendixonC++/QtprogrammingforexperiencedJava
developers


TheaccompanyingCD-ROMincludestheopensourceeditionofQt4.1.1forWindows,Mac,
Linux,andmanyUnixes,aswellasMinGW,asetoffreelyavailabledevelopmenttoolsthat
canbeusedtobuildQtapplicationsonWindows,andalsothesourcecodeforthebook's
examples.


C++GUIProgrammingwithQt4
ByJasminBlanchette,MarkSummerfield
...............................................
Publisher:PrenticeHall
PubDate:June21,2006
PrintISBN-10:0-13-187249-4
PrintISBN-13:978-0-13-187249-3
Pages:560

TableofContents|Index















































Copyright
Foreword
Preface
Acknowledgments
ABriefHistoryofQt
Part1:BasicQt
Chapter1.GettingStarted
HelloQt
MakingConnections
LayingOutWidgets
UsingtheReferenceDocumentation
Chapter2.CreatingDialogs
SubclassingQDialog
SignalsandSlotsinDepth
RapidDialogDesign
Shape-ChangingDialogs
DynamicDialogs
Built-inWidgetandDialogClasses
Chapter3.CreatingMainWindows
SubclassingQMainWindow
CreatingMenusandToolbars
SettingUptheStatusBar
ImplementingtheFileMenu
UsingDialogs




















































































StoringSettings
MultipleDocuments
SplashScreens
Chapter4.ImplementingApplicationFunctionality
TheCentralWidget
SubclassingQTableWidget
LoadingandSaving
ImplementingtheEditMenu
ImplementingtheOtherMenus

SubclassingQTableWidgetItem
Chapter5.CreatingCustomWidgets
CustomizingQtWidgets
SubclassingQWidget
IntegratingCustomWidgetswithQtDesigner
DoubleBuffering
PartII:IntermediateQt
Chapter6.LayoutManagement
LayingOutWidgetsonaForm
StackedLayouts
Splitters
ScrollingAreas
DockWidgetsandToolbars
MultipleDocumentInterface
Chapter7.EventProcessing
ReimplementingEventHandlers
InstallingEventFilters
StayingResponsiveDuringIntensiveProcessing
Chapter8.2Dand3DGraphics
PaintingwithQPainter
PainterTransformations
High-QualityRenderingwithQImage
Printing
GraphicswithOpenGL
Chapter9.DragandDrop
EnablingDragandDrop
SupportingCustomDragTypes
ClipboardHandling
Chapter10.ItemViewClasses
UsingtheItemViewConvenienceClasses




















































































UsingPredefinedModels
ImplementingCustomModels
ImplementingCustomDelegates
Chapter11.ContainerClasses
SequentialContainers
AssociativeContainers
GenericAlgorithms
Strings,ByteArrays,andVariants
Chapter12.Input/Output

ReadingandWritingBinaryData
ReadingandWritingText
TraversingDirectories
EmbeddingResources
Inter-ProcessCommunication
Chapter13.Databases
ConnectingandQuerying
PresentingDatainTabularForm
ImplementingMasterDetailForms
Chapter14.Networking
WritingFTPClients
WritingHTTPClients
WritingTCPClientServerApplications
SendingandReceivingUDPDatagrams
Chapter15.XML
ReadingXMLwithSAX
ReadingXMLwithDOM
WritingXML
Chapter16.ProvidingOnlineHelp
Tooltips,StatusTips,and"What'sThis?"Help
UsingQTextBrowserasaSimpleHelpEngine
UsingQtAssistantforPowerfulOnlineHelp
PartIII:AdvancedQt
Chapter17.Internationalization
WorkingwithUnicode
MakingApplicationsTranslation-Aware
DynamicLanguageSwitching
TranslatingApplications
Chapter18.Multithreading
CreatingThreads




















































SynchronizingThreads
CommunicatingwiththeMainThread
UsingQt'sClassesinSecondaryThreads
Chapter19.CreatingPlugins
ExtendingQtwithPlugins
MakingApplicationsPlugin-Aware
WritingApplicationPlugins
Chapter20.Platform-SpecificFeatures
InterfacingwithNativeAPIs
UsingActiveXonWindows

HandlingX11SessionManagement
Chapter21.EmbeddedProgramming
GettingStartedwithQtopia
CustomizingQtopiaCore
AppendixA.InstallingQt
ANoteonLicensing
InstallingQt/Windows
InstallingQt/Mac
InstallingQt/X11
AppendixB.IntroductiontoC++forJavaandC#Programmers
GettingStartedwithC++
MainLanguageDifferences
TheStandardC++Library
AbouttheAuthors
Production
Index


Copyright
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andthepublisherwas
awareofatrademarkclaim,thedesignationshavebeenprinted
withinitialcapitallettersorinallcapitals.
Theauthorsandpublisherhavetakencareinthepreparationof
thisbook,butmakenoexpressedorimpliedwarrantyofany
kindandassumenoresponsibilityforerrorsoromissions.No
liabilityisassumedforincidentalorconsequentialdamagesin
connectionwithorarisingoutoftheuseoftheinformationor
programscontainedherein.

Thepublisheroffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales,which
mayincludeelectronicversionsand/orcustomcoversand
contentparticulartoyourbusiness,traininggoals,marketing
focus,andbrandinginterests.Formoreinformation,please
contact:
U.S.CorporateandGovernmentSales
(800)382-3419

ForsalesoutsidetheUnitedStates,pleasecontact:
InternationalSales

VisitusontheWeb:www.prenhallprofessional.com


LibraryofCongressCataloging-in-PublicationData
Blanchette,Jasmin.
C++GUIprogrammingwithQt4/JasminBlanchette,MarkSummerfield
p.cm.
Includesbibliographicalreferencesandindex.
ISBN0-13-187249-4(pbk.:alk.paper)
1.Graphicaluserinterfaces(Computersystems)2.C++(Computerprog
I.Summerfield,Mark.II.Title.
QA76.9.U83B5322006
005.4'37dc22
2006013376
Copyright©2006TrolltechAS
Allrightsreserved.PrintedintheUnitedStatesofAmerica.This
publicationmayonlybedistributedsubjecttothetermsand
conditionssetforthintheOpenPublicationLicense,v1.0or

later(thelatestversionisavailableat />Trolltech®,Qt®,Qtopia®,andtheTrolltechandQtopialogos
areregisteredtrademarksofTrolltechAS.
TextprintedintheUnitedStatesonrecycledpaperatCourierin
Stoughton,Massachusetts.
Firstprinting,June2006


Foreword
WhyQt?WhydoprogrammerslikeuschooseQt?Sure,there
aretheobviousanswers:Qt'ssingle-sourcecompatibility,its
featurerichness,itsC++performance,theavailabilityofthe
sourcecode,itsdocumentation,thehigh-qualitytechnical
support,andalltheotheritemsmentionedinTrolltech'sglossy
marketingmaterials.Thisisallverywell,butitmissesthemost
importantpoint:Qtissuccessfulbecauseprogrammerslikeit.
Howcomeprogrammerslikeonetechnology,butdislike
another?PersonallyIbelievesoftwareengineersenjoy
technologythatfeelsright,butdislikeeverythingthatdoesn't.
"Feelsright"meansmanythings.IntheQt3editionofthe
book,ImentionedTrolltech'sphonesystemasaparticularly
goodexampleofsomeparticularlybadtechnology.Thephone
systemdidn'tfeelright,becauseitforcedustodoapparently
randomthingsdependingonsomeequallyrandomcontext.
Randomnessdoesn'tfeelright.Anotherthingthatdoesn'tfeel
rightisrepetitivenessandredundancy.Goodprogrammersare
lazy.Whatweloveaboutcomputerscomparedto,say,
gardeningisthatwedon'thavetodothesamethingsoverand
over.
Letmeemphasizethispointwithareal-worldexample:travel
reimbursementforms.Typicallythoseformscomeasfancy

spreadsheets;youfillthemout,andyougetrealmoney.Simple
technology,oneshouldthink,andgiventhemonetaryincentive
thisshouldbeasimpletaskforagrown-upengineer.
Realitylooksdifferent,though.Whilenobodyelseinthe
companyseemstohaveanyproblemswhatsoeverdealingwith
thoseforms,theengineersdo.Andhavingtalkedtopeoplein
othercompanies,thisseemstobeacommonpattern.Wedefer
reimbursementuntiltheverylastmoment,andsometimeswe
mightevenforgetaboutit.Whyisthat?Lookingatourform,


it'sastraightforward,standardprocedure.Onehastocollect
receipts,numberthem,andputthosenumbersintotheproper
fieldswiththedate,thelocation,adescription,andtheamount.
Thenumberingandcopyingisdesignedtoeasesomeone's
work,butstrictlyspeakingitisredundant,giventhatthedate,
location,description,andamountunambiguouslyidentifya
receipt.Atinybitofextraworktogetyourmoneyback,one
wouldthink.
Asmallannoyanceistheper-diemrate,though,whichdepends
onthetravellocation.There'ssomeseparatedocument
somewherethatliststhestandardizedratesforallthedifferent
travellocations.Youcan'tjustselect"Chicago";insteadyou
havetolookuptherateforChicagoyourself.There'sasimilar
annoyancewiththeexchangeratefield.Onehastofindthe
currentexchangeratesomewhereperhapswithGoogle's
helpandthenentertherateineverysinglefield.Well,strictly
speaking,youshouldwaitforyourcreditcardcompanytoissue
astatementtoyouwiththeactualexchangeratethatthey
used.Whilethisisnothardtodo,lookingupdifferentpiecesof

informationfromdifferentsources,andthencopyingthe
relevantitemstoseveralplacesintheformfeelsneedlessly
awkward.
Programmingcanbealotlikefillingintravelreimbursement
forms,onlyworse.AndthisiswhereQtcomestotherescue.Qt
isdifferent.Foronething,Qtmakessense.Andforanother,Qt
isfun.Qtletsyouconcentrateonyourtasks.WhenQt'soriginal
architectsfacedaproblem,theydidn'tjustlookforagood
solution,orthesimplestsolution.Theylookedfortheright
solution,andthentheydocumentedit.Grantedtheymade
mistakes,andgrantedsomeoftheirdesigndecisionsdidn't
passthetestoftime,buttheystillgotalotofthingsright,and
whatwasn'trightcouldandcanbecorrected.Youcanseethis
bythefactthatasystemoriginallydesignedtobridgeWindows
95andUnix/Motifnowunifiesmoderndesktopsystemsas
diverseasWindowsXP,MacOSX,andGNU/Linux,andprovides


thefoundationfortheQtopiaapplicationplatformforembedded
Linux.
LongbeforeQtbecamesopopularandsowidelyused,the
dedicationofQt'sdeveloperstofindingtherightsolutionsmade
Qtspecial.Thatdedicationisjustasstrongtodayandaffects
everyonewhodevelopsandmaintainsQt.Forus,workingonQt
isaresponsibilityandaprivilege.Weareproudofhelpingto
makeyourprofessionalandopensourceliveseasierandmore
enjoyable.
MatthiasEttrich
Oslo,Norway
June2006



Preface
QtisacomprehensiveC++frameworkfordevelopingcrossplatformGUIapplicationsusinga"writeonce,compile
anywhere"approach.Qtletsprogrammersuseasinglesource
treeforapplicationsthatwillrunonWindows98toXP,MacOS
X,Linux,Solaris,HP-UX,andmanyotherversionsofUnixwith
X11.TheQtlibrariesandtoolsarealsopartofQtopiaCore,a
productthatprovidesitsownwindowsystemontopof
embeddedLinux.
ThepurposeofthisbookistoteachyouhowtowriteGUI
programsusingQt4.Thebookstartswith"HelloQt"and
quicklyprogressestomoreadvancedtopics,suchascreating
customwidgetsandprovidingdraganddrop.Thetextis
complementedbyaCDthatcontainsthesourcecodeofthe
exampleprograms.TheCDalsoincludestheopensource
editionofQt4.1.1forallsupportedplatforms,aswellas
MinGW,asetoffreelyavailabledevelopmenttoolsthatcanbe
usedtobuildQtapplicationsonWindows.AppendixAexplains
howtoinstallthesoftware.
Thebookisdividedintothreeparts.PartIcoversallthe
conceptsandpracticesnecessaryforprogrammingGUI
applicationsusingQt.Knowledgeofthispartaloneissufficient
towriteusefulGUIapplications.PartIIcoverscentralQttopics
ingreaterdepth,andPartIIIprovidesmorespecializedand
advancedmaterial.ThechaptersofPartsIIandIIIcanberead
inanyorder,buttheyassumefamiliaritywiththecontentsof
PartI.
ReadersoftheQt3editionofthisbookwillfindthisnewedition
familiarinbothcontentandstyle.Thiseditionhasbeen

updatedtotakeadvantageofQt4'snewfeatures(including
somethatwereintroducedwithQt4.1)andtopresentcode
thatshowsgoodidiomaticQt4programmingtechniques.In


manycases,wehaveusedexamplessimilartotheonesusedin
theQt3edition.Thiswillnotaffectnewreaders,butwillhelp
thosewhoreadthepreviouseditionorientthemselvestoQt4's
cleaner,clearer,andmoreexpressivestyle.
ThiseditionincludesnewchapterscoveringQt4'smodel/view
architecture,thenewpluginframework,andembedded
programmingwithQtopia,aswellanewappendix.Andjustlike
theQt3book,theemphasisisonexplainingQtprogramming
ratherthansimplyrehashingorsummarizingQt'sextensive
onlinedocumentation.
Wehavewrittenthebookwiththeassumptionthatyouhavea
basicknowledgeofC++,Java,orC#.Thecodeexamplesusea
subsetofC++,avoidingmanyC++featuresthatarerarely
neededwhenprogrammingQt.Inthefewplaceswhereamore
advancedC++constructisunavoidable,itisexplainedwhereit
isused.
IfyoualreadyknowJavaorC#buthavelittleornoexperience
withC++,werecommendthatyoubeginbyreadingAppendix
B,whichprovidessufficientintroductiontoC++tobeableto
usethisbook.ForamorethoroughintroductiontoobjectorientedprogramminginC++,werecommendC++Howto
ProgrambyHarveyDeitelandPaulDeitel,andtheC++Primer
byStanleyB.Lippman,JoséeLajoie,andBarbaraE.Moo.
Qtmadeitsreputationasacross-platformframework,but
becauseofitsintuitiveandpowerfulAPI,manyorganizations
useQtforsingle-platformdevelopment.AdobePhotoshop

Albumisjustoneexampleofamass-marketWindows
applicationwritteninQt.Manysophisticatedsoftwaresystems
inverticalmarkets,suchas3Danimationtools,digitalfilm
processing,electronicdesignautomation(forchipdesign),oil
andgasexploration,financialservices,andmedicalimaging,
arebuiltwithQt.Ifyouaremakingalivingwithasuccessful
WindowsproductwritteninQt,youcaneasilycreatenew
marketsintheMacOSXandLinuxworldssimplyby


recompiling.
Qtisavailableundervariouslicenses.Ifyouwanttobuild
commercialapplications,youmustbuyacommercialQtlicense;
ifyouwanttobuildopensourceprograms,youcanusethe
opensource(GPL)edition.QtisthefoundationonwhichtheK
DesktopEnvironment(KDE)andthemanyopensource
applicationsthatgowithitarebuilt.
InadditiontoQt'shundredsofclasses,thereareadd-onsthat
extendQt'sscopeandpower.Someoftheseproducts,likeQt
ScriptforApplications(QSA)andtheQtSolutionscomponents,
areavailablefromTrolltech,whileothersaresuppliedbyother
companiesandbytheopensourcecommunity.See
forinformationon
Qtadd-ons.Qtalsohasawell-establishedandthrivinguser
communitythatusestheqt-interestmailinglist;see
fordetails.
Ifyouspoterrorsinthebook,havesuggestionsforthenext
edition,orwanttogiveusfeedback,wewouldbedelightedto
hearfromyou.YoucanreachusatThe
erratawillbeplacedon />


Acknowledgments
OurfirstacknowledgmentisofEirikChambe-Eng,Trolltech's
president.Eiriknotonlyenthusiasticallyencouragedustowrite
theQt3editionofthebook,healsoallowedustospenda
considerableamountofourworktimewritingit.Eirikand
TrolltechCEOHaavardNordbothreadthemanuscriptand
providedvaluablefeedback.Theirgenerosityandforesightwas
aidedandabettedbyMatthiasEttrich,Trolltech'slead
developer.Matthiascheerfullyacceptedourneglectofdutyas
weobsessedoverthewritingofthefirsteditionofthisbook
andgaveusalotofadviceongoodQtprogrammingstyle.
FortheQt3edition,weaskedtwoQtcustomers,PaulCurtis
andKlausSchmidinger,tobeourexternalreviewers.Bothare
Qtexpertswithanamazingattentiontotechnicaldetail,which
theyprovedbyspottingsomeverysubtleerrorsinour
manuscriptandsuggestingnumerousimprovements.And
withinTrolltech,alongsideMatthias,ourmoststalwartreviewer
wasReginaldStadlbauer.Histechnicalinsightwasinvaluable,
andhetaughtushowtodosomethingsinQtthatwedidn't
evenknowwerepossible.
ForthisQt4edition,wehavecontinuedtobenefitfromthe
unstintinghelpandsupportofEirik,Haavard,andMatthias.
KlausSchmidingercontinuedtogivevaluablefeedback,and
withinTrolltech,ourkeyreviewerswereAndreasAardal
Hanssen,HenrikHartz,ViviGlückstadKarlsen,TrentonSchulz,
AndyShaw,andPåldeVibe.
Inadditiontothereviewersmentionedabove,wereceived
experthelpfromHaraldFernengel(databases),Volker
Hilsheimer(ActiveX),BradleyHughes(multithreading),Trond

Kjernåsen(3Dgraphicsanddatabases),LarsKnoll(2Dgraphics
andinternationalization),SamMagnuson(qmake),MariusBugge
Monsen(itemviewclasses),DimitriPapadopoulos(Qt/X11),


PaulOlavTvete(customwidgetsandembeddedprogramming),
RainerSchmid(networkingandXML),AmritPalSingh
(introductiontoC++),andGunnarSletta(2Dgraphicsand
eventprocessing).
ExtrathanksareduetoTrolltech'sdocumentationandsupport
teamsforhandlingdocumentation-relatedissueswhilethebook
consumedsomuchofourtime,andtoTrolltech'ssystem
administratorsforkeepingourmachinesrunningandour
networkscommunicatingthroughouttheproject.
Ontheproductionside,TrentonSchulzcreatedthe
accompanyingCD,andTrolltech'sCathrineBorehandledthe
contractsandlegalitiesonourbehalf.ThanksalsotoNathan
ClementfortheTrollillustrations.Andlastbutnotleast,thanks
toLaraWysongfromPearsons,forhandlingtheproduction
practicalitiessowell.


ABriefHistoryofQt
TheQtframeworkfirstbecamepubliclyavailableinMay1995.
ItwasinitiallydevelopedbyHaavardNord(Trolltech'sCEO)and
EirikChambe-Eng(Trolltech'spresident).HaavardandEirikmet
attheNorwegianInstituteofTechnologyinTrondheim,where
theybothgraduatedwithmaster'sdegreesincomputerscience.
Haavard'sinterestinC++GUIdevelopmentbeganin1988
whenhewascommissionedbyaSwedishcompanytodevelopa

C++GUIframework.Acoupleofyearslater,inthesummerof
1990,HaavardandEirikwereworkingtogetheronaC++
databaseapplicationforultrasoundimages.Thesystemneeded
tobeabletorunwithaGUIonUnix,Macintosh,andWindows.
Onedaythatsummer,HaavardandEirikwentoutsidetoenjoy
thesunshine,andastheysatonaparkbench,Haavardsaid,
"Weneedanobject-orienteddisplaysystem."Theresulting
discussionlaidtheintellectualfoundationfortheobject-oriented
cross-platformGUIframeworktheywouldsoongoontobuild.
In1991,Haavardstartedwritingtheclassesthateventually
becameQt,collaboratingwithEirikonthedesign.Thefollowing
year,Eirikcameupwiththeideafor"signalsandslots",a
simplebutpowerfulGUIprogrammingparadigmthathasnow
beenembracedbyseveralothertoolkits.Haavardtooktheidea
andproducedahand-codedimplementation.By1993,Haavard
andEirikhaddevelopedQt'sfirstgraphicskernelandwereable
toimplementtheirownwidgets.Attheendoftheyear,
Haavardsuggestedthattheygointobusinesstogethertobuild
"theworld'sbestC++GUIframework".
Theyear1994beganinauspiciouslywiththetwoyoung
programmerswantingtoenterawell-establishedmarket,with
nocustomers,anunfinishedproduct,andnomoney.
Fortunately,boththeirwiveswereemployedandthereforeable
tosupporttheirhusbandsforthetwoyearsEirikandHaavard


expectedtoneedtodeveloptheproductandstartearningan
income.
Theletter'Q'waschosenastheclassprefixbecausetheletter
lookedbeautifulinHaavard'sEmacsfont.The't'wasaddedto

standfor"toolkit",inspiredbyXt,theXToolkit.Thecompany
wasincorporatedonMarch4,1994,originallyasQuasar
Technologies,thenasTrollTech,andtodayasTrolltech.
InApril1995,thankstoacontactmadethroughoneof
Haavard'suniversityprofessors,theNorwegiancompanyMetis
gavethemacontracttodevelopsoftwarebasedonQt.Around
thistime,TrolltechhiredArntGulbrandsen,whoduringhissix
yearsatTrolltechdevisedandimplementedaningenious
documentationsystemaswellascontributingtoQt'scode.
OnMay20,1995,Qt0.90wasuploadedtosunsite.unc.edu.Six
dayslater,thereleasewasannouncedoncomp.os.linux.announce.
ThiswasQt'sfirstpublicrelease.Qtcouldbeusedforboth
WindowsandUnixdevelopment,offeringthesameAPIonboth
platforms.Qtwasavailableundertwolicensesfromdayone:A
commerciallicensewasrequiredforcommercialdevelopment,
andafreesoftwareeditionwasavailableforopensource
development.TheMetiscontractkeptTrolltechafloat,whilefor
tenlongmonthsnooneboughtacommercialQtlicense.
InMarch1996,theEuropeanSpaceAgencybecamethesecond
Qtcustomer,withapurchaseoftencommerciallicenses.With
unwaveringfaith,EirikandHaavardhiredanotherdeveloper.Qt
0.97wasreleasedattheendofMay,andonSeptember24,
1996,Qt1.0cameout.Bytheendoftheyear,Qthadreached
version1.1;eightcustomers,eachinadifferentcountry,had
bought18licensesbetweenthem.Thisyearalsosawthe
foundingoftheKDEproject,ledbyMatthiasEttrich.
Qt1.2wasreleasedinApril1997.MatthiasEttrich'sdecisionto
useQttobuildKDEhelpedQtbecomethedefactostandardfor
C++GUIdevelopmentonLinux.Qt1.3wasreleasedin



September1997.
MatthiasjoinedTrolltechin1998,andthelastmajorQt1
release,1.40,wasmadeinSeptemberofthatyear.Qt2.0was
releasedinJune1999.Qt2hadanewopensourcelicense,the
QPublicLicense(QPL),whichcompliedwiththeOpenSource
Definition.InAugust1999,QtwontheLinuxWorldawardfor
bestlibrary/tool.Aroundthistime,TrolltechPtyLtd(Australia)
wasestablished.
TrolltechreleasedQtopiaCore(thencalledQt/Embedded)in
2000.ItwasdesignedtorunonembeddedLinuxdevicesand
provideditsownwindowsystemasalightweightreplacement
forX11.BothQt/X11andQtopiaCorewerenowofferedunder
thewidelyusedGNUGeneralPublicLicense(GPL)aswellas
undercommerciallicenses.Bytheendof2000,Trolltechhad
establishedTrolltechInc.(USA)andhadreleasedthefirst
versionofQtopia,anapplicationplatformformobilephones
andPDAs.QtopiaCorewontheLinuxWorld"BestEmbedded
LinuxSolution"awardinboth2001and2002,andQtopiaPhone
achievedthesamedistinctionin2004.
Qt3.0wasreleasedin2001.QtwasnowavailableonWindows,
MacOSX,Unix,andLinux(desktopandembedded).Qt3
provided42newclassesanditscodeexceeded500,000lines.
Qt3wasamajorstepforwardfromQt2,includingconsiderably
improvedlocaleandUnicodesupport,acompletelynewtext
viewingandeditingwidget,andaPerl-likeregularexpression
class.Qt3wontheSoftwareDevelopmentTimes"Jolt
ProductivityAward"in2002.
Inthesummerof2005,Qt4.0wasreleased.Withabout500
classesandmorethan9000functions,Qt4islargerandricher

thananypreviousversion,andithasbeensplitintoseveral
librariessothatdevelopersonlyneedtolinkagainsttheparts
ofQtthattheyneed.Qt4isahugeadvanceonprevious
versionswithimprovementsthatincludeacompletelynewset
ofefficientandeasy-to-usetemplatecontainers,advanced


model/viewfunctionality,afastandflexible2Dpainting
framework,andpowerfulUnicodetextviewingandediting
classes,nottomentionthousandsofsmallerenhancements
acrossthecompleterangeofQtclasses.Qt4isthefirstQt
editiontobeavailableforbothcommercialandopensource
developmentonalltheplatformsitsupports.
Alsoin2005,TrolltechopenedarepresentativeofficeinBeijing
toprovidecustomersinChinaandtheregionwithsales
services,training,andtechnicalsupportforQtopia.
SinceTrolltech'sbirth,Qt'spopularityhasgrownunabatedand
continuestogrowtothisday.Thissuccessisareflectionboth
ofthequalityofQtandofhowenjoyableitistouse.Inthelast
decade,Qthasgonefrombeingaproductusedbyaselectfew
"intheknow"toonethatisuseddailybythousandsof
customersandtensofthousandsofopensourcedevelopersall
aroundtheworld.




Part1:BasicQt
Chapter1.GettingStarted
Chapter2.CreatingDialogs

Chapter3.CreatingMainWindows
Chapter4.ImplementingApplicationFunctionality
Chapter5.CreatingCustomWidgets


Chapter1.GettingStarted

HelloQt
MakingConnections
LayingOutWidgets
UsingtheReferenceDocumentation
ThischaptershowshowtocombinebasicC++withthe
functionalityprovidedbyQttocreateafewsmallgraphicaluser
interface(GUI)applications.Thischapteralsointroducestwo
keyQtideas:"signalsandslots"andlayouts.InChapter2,we
willgointomoredepth,andinChapter3,wewillstartbuilding
amorerealisticapplication.
IfyoualreadyknowJavaorC#buthavelimitedexperience
withC++,youmightwanttostartbyreadingtheC++
introductioninAppendixB.




HelloQt
Let'sstartwithaverysimpleQtprogram.Wewillfirststudyit
linebyline,thenwewillseehowtocompileandrunit.
1#include<QApplication>
2#include<QLabel>
3intmain(intargc,char*argv[])

4{
5QApplicationapp(argc,argv);
6QLabel*label=newQLabel("HelloQt!");
7label->show();
8returnapp.exec();
9}

Lines1and2includethedefinitionsoftheQApplicationandQLabel
classes.ForeveryQtclass,thereisaheaderfilewiththesame
name(andcapitalization)astheclassthatcontainstheclass's
definition.
Line5createsaQApplicationobjecttomanageapplication-wide
resources.TheQApplicationconstructorrequiresargcandargv
becauseQtsupportsafewcommand-lineargumentsofitsown.
Line6createsaQLabelwidgetthatdisplays"HelloQt!".InQt
andUnixterminology,awidgetisavisualelementinauser
interface.Thetermstemsfrom"windowgadget"andisthe
equivalentofboth"control"and"container"inWindows
terminology.Buttons,menus,scrollbars,andframesareall
examplesofwidgets.Widgetscancontainotherwidgets;for
example,anapplicationwindowisusuallyawidgetthat
containsaQMenuBar,afewQToolBars,aQStatusBar,andsomeother
widgets.MostapplicationsuseaQMainWindoworaQDialogasthe
applicationwindow,butQtissoflexiblethatanywidgetcanbe


awindow.Inthisexample,theQLabelwidgetistheapplication
window.
Line7makesthelabelvisible.Widgetsarealwayscreated
hidden,sothatwecancustomizethembeforeshowingthem,

therebyavoidingflicker.
Line8passescontroloftheapplicationontoQt.Atthispoint,
theprogramenterstheeventloop.Thisisakindofstand-by
modewheretheprogramwaitsforuseractionssuchasmouse
clicksandkeypresses.Useractionsgenerateevents(also
called"messages")towhichtheprogramcanrespond,usually
byexecutingoneormorefunctions.Forexample,whenthe
userclicksawidget,a"mousepress"anda"mouserelease"
eventaregenerated.Inthisrespect,GUIapplicationsdiffer
drasticallyfromconventionalbatchprograms,whichtypically
processinput,produceresults,andterminatewithouthuman
intervention.
Forsimplicity,wedon'tbothercallingdeleteontheQLabelobject
attheendofthemain()function.Thismemoryleakisharmless
insuchasmallprogram,sincethememorywillbereclaimedby
theoperatingsystemwhentheprogramterminates.

Figure1.1.HelloonLinux

Itisnowpossibletotrytheprogramonyourownmachine.
First,youwillneedtoinstallQt4.1.1(oralaterQt4release),a
processthatisexplainedinAppendixA.Fromnowon,wewill
assumethatyouhaveacorrectlyinstalledcopyofQt4andthat
Qt'sbindirectoryisinyourPATHenvironmentvariable.(On


Windows,thisisdoneautomaticallybytheQtinstallation
program.)Youwillalsoneedtheprogram'ssourcecodeinafile
calledhello.cppinadirectorycalledhello.Youcantypein
hello.cppyourself,orcopyitfromtheCDprovidedwiththis

book,whereitisavailableas/examples/chap01/hello/hello.cpp.
Fromacommandprompt,changethedirectorytohello,then
type
qmake-project

tocreateaplatform-independentprojectfile(hello.pro),then
type
qmakehello.pro

tocreateaplatform-specificmakefilefromtheprojectfile.
Typemaketobuildtheprogram.[*]Runitbytypinghelloon
Windows,./helloonUnix,andopenhello.apponMacOSX.To
terminatetheprogram,clicktheclosebuttoninthewindow's
titlebar.
[*]Ifyougetacompilererroronthe<QApplication>include,itprobablymeansthatyouareusinganolder
versionofQt.MakesurethatyouareusingQt4.1.1oralaterQt4release.

IfyouareusingWindowsandhaveinstalledtheQtOpen
SourceEditionandtheMinGWcompiler,youwillhavea
shortcuttoaDOSPromptwindowthathasalltheenvironment
variablescorrectlysetupforQt.Ifyoustartthiswindow,you
cancompileQtapplicationswithinitusingqmakeandmakeas
describedabove.Theexecutablesproducedareputinthe
application'sdebugorreleasefolder,forexample,C:\qtbook\hello\release\hello.exe.


×