The book of qt 4 the art of building qt applications - phần 2 docx

45 377 0
The book of qt 4 the art of building qt applications - phần 2 docx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

1 Basics,Tools, and First Code #include <QtGui> However,these libraryheaderfilesare verylong,which considerablyincreasesthe length of thecompilingprocess.Thiswon’t be aproblemifthe compilersupports precompiledheaderfiles, butonlythemorerecentcompilers do (suchaswithGCC from version 3.4on). TheBaseLibraryQtCore QtCoreisapartiallibraryrequired byeveryQt program.Among otherthings, it makesavailable thefollowing: Basic datatypes, such as QStringand QByteArray Basicdatastructures, such as QList, QVector, andQHash Input/output classessuchasQIODevice, QTextStream, andQFile Classeswithwhich multiplethreads can be programmed(includingQWaitCon- dition andQThread) TheclassesQObject andQCoreApplication(thebaseclass for QApplication) None of theseclassesdepends on GUI components.Thisseparationfromthe GUI allowsQtapplications (suchascommand-lineprograms) to be written that do not implementaGUI In nongraphical programs theQCoreApplicationclass takesonthe role of theQAp- plicationclass in GUI applications:Itmakesaneventloop available.Thisisuseful if you requireasynchronouscommunication,whether between different threads or via networksockets. 11 TheGUI LibraryQtGui TheQtGui librarycontains allclassesthatare necessaryfor program ming graph ical user in terfaces,including thefollowing: TheQWidgetclass andclassesderived from it,suchasQLabeland QPushButton Thelayoutclasses(includingQVBoxLayout, QHBoxLayout, andQGridLayout) ClassessuchasQMainWindowandQMenu, which areneeded if you wanttoadd menus to an application 11 QtCore doesnot containanynetworkclasses, butthe QtNetworklibrarycanbeusedwith QtCore if networking is required. 44 1.5 Qt at aGlance Classesfor drawing, such as QPainter,QPen, andQBrush Classesprovidingready-to-usedialogs (including QFileDialog andQPrintDialog) TheQApplicationclass QtGui requires theQtCorelibrary. TheNetworkLibraryQtNetwork Thepartial libraryQtNetworkprovides classesfor writing networkapplications. In addition to supporting simple socketcommunication via theQTcpSocketand QUdpSocketclasses, this libraryalso enablesclient-sideHTTP andFTP withQHttp andQFtp. UnlikeQtGui,QtNetworkrequiresthe QtCorelibrary,but it can,ofcourse, be used together withQtGui andthe otherlibraries. TheOpenGLLibraryQtOpenGL TheQtOpenGL libraryenablesOpenGLtobeusedinaQt program.Itprovides the QGLWidgetclass—aQtwidgetinwhich you can drawusingOpenGLcommands. QtOpenGL uses theQtCoreand QtGui libraries. TheDatabaseLibraryQtSql TheQtSql libraryclassesprovideaccess to SQLdatabases in Qt programs. This library includes classesthatare used to establishaconnectionwithanSQL databaseand to queryandmodifydata.Qtsupports arange of SQLdatabases,including the opensourcedatabases PostgreSQL,MySQL, andSQLite. QtSqlrequiresthe QtCorelibrary,and it is discussedatlengthinChapter 9(page 257). TheXML LibraryQtXml Asimple, nonvalidatingXML parser is provided bythepartial libraryQtXML.Itcan be addresseddirectlythroughaSAX2 interface(SimpleAPI forXML). QtXml also contains an implementation of theDOM standard(Document Ob ject Model ). Thecorresponding classesallowyou to parse an XMLdocument,manipu- late itstreestructure,publishthe modifieddocument againasanXML document, or to create anewXMLdocument withDOM. 45 1 Basics,Tools, and First Code This libraryrequires onlytheQtCorelibrary,and it is discussedinmoredepth in Chapter 13 (page 353). TheCompatibilityLibraryQt3Support Comparedwithits predecessor, Qt 3, Qt 4has undergoneconsiderable develop- ment:Someclassescontain changesthatare incompatible withthe Qt 3versions, andothershavebeen replaced in Qt 4withcompletelynewclasseswithdifferent names. In ordertosimplifytheporting of Qt 3programstoQt4,Trolltechincludes thecorresponding Qt 3classesinthe Qt3Supportlibrary.However,you should not usethislibraryfor newprograms, sincedevelopmentoftheir classeshas stopped. Since this book explains programming withQt4,wewillnot usethese classesand willnot discussthemfurther. TheVectorGraphicsLibraryQtSvg TheSVG vectorgraphicsformat, publishedbytheW3consortiumand basedon XML, hasgreat potential.FromQt4.1 onwardthe QtSvglibrarysupports theSVG profiles SVGBasic and SVGTiny, 12 which can be used to displaySVGfilesand animations,althoughitcannotasyet create them or,asinXML,manipulatethem throughaDOM tree. TheQtAssistantClientLibrary Theassistantclient libraryallowsyou to remotelycontrolthe Qt assistantapplica- tion.Thisallowsyou to usethe assistantasaplatform-independenthelpbrowser for yourapplication. Theheart of themodule is theQAssistantClient class. Customized help pagesfor usewithQtassistantare provided in basicHTMLmarkup, alongwithanXML filethatdescribesthe structureofthe documentation. TheTestCaseLibraryQTestLib Originallyreleased outsidethe Qt core distribution for payingcustomers, QTestLib entered theregular Qt distribution starting withthe Qt 4.1.0release. Thelibrary contains facilitiestowrite properunittests for newlywritten classes, andcoversa scope similartoJUnit in Java. 12 Seehttp://www.w3.org/TR/SVGMobile/. 46 1.5 Qt at aGlance TheQtDBusLibrary DBus is amessaging protocol that hasemerged as adefactostandardonLinuxand otherUnixderivates.For instance,the LinuxHardwareAbstractionLayer (HAL)and theupcomingKDE 4are usingDBusfor interprocesscommunication.Even though ports for Windowsand MacOSXexist, Qt 4.2willoffertobuild this libraryonlyon Unix.Thismay,however,changeinfutureversions. ActiveQt andMigration Classes Theplatform-specificextension ActiveQt for Windowsmakesitpossible to imple- ment ActiveXcomponents withQtand to usetheminQtprograms. It is available onlyin thecommercialQtdesktop edition, however. Trolltechalsoprovides migrationsolutions for MFC-,Motif-, andXt-basedappli- cations. Like ActiveQt,however,theyareavailable onlyas separatecommercial add-ons for Qt 4, the Qt Solutions , 13 andwillnot be discussedinthisbook. 1.5.2Toolsand Utilities In addition to allthis, Qt includes threeGUI programsthatcan be used to display Qt documentation, create dialogs accordingtothe WYSIWYGprinciple ( What You See Is What YouGet), or translateprogramsintoother languages. Thetoolkitalso provides aseriesofcommand-lineprogramsfor performing various tasks. TheDocumentation Browser“Qt Assistant” TheQtdocumentationconsistsofsimpleHTMLfilesthatcan be viewed withany web browserorwiththe Qt Assistant. Unlikeaweb br owser, theAssistantdisplays an indexof theentireQtdocumentationand allowsfor afull-textsearchofthat documentation(Figure 1.10). TheAssistant’skeyworddirectoryis particularlyuseful whenworking wit hQtdaily. Forexample, if you requiredocumentationonaclass, on QLabel,simplyenter qlabel in theindexinputbox.With ✞ ✝ ☎ ✆ Enter you aretakenimmediatelyto theexcellent class documentation. 13 Seehttp://www.trolltech.com/products/solutions/. 47 1 Basics,Tools, and First Code Figure 1.10: TheQtAssistant displays theQt documentation. TheAssistantisanimportant complement to this book because it notonlydoc- umentsnewlyaddedAPI calls (oronesnot discussedinthisbook duetolack of space), butalsoprovides additionalusage examples. 14 TheGUI Editor “QtDesigner” TheQtDesignerallowsyou to create applicationdialogs andthe main application windowin aWYSIWYG fashion(Figure 1.11),which is particularlyuseful when creating complexdialogs andlayouts.You can addwidgets in theDesignervia drag anddropand settheir properties. Forexample, you can chan ge thetextofa QLabel or itscolor andtypeface. Youcan usethe Designer to combineseveral widgets in alayout, andimmediately seethe effect that thelayouthas on thewindow.You can even setupsignal/slot connections between th ewidgets andthe Designer,ifnecessary. TheDesigner’spreviewmode allowsyou to checkthe GUIsyou’vecreated:You can seehowthelayouts react to changesinsize, testthe widgets,and seewhether the signal/slotconnections havethe desiredeffects. TheDesigneralsohas amode that specifies the tabsequence of thewidgets;that is,the orderinwhich theuseraccessesthe individualwidgets whenpressing ✞ ✝ ☎ ✆ tab repeatedly.Thisisanimportant aspect of auserinterface, andone that you should alwayscheck. Aprogram can onlybe operated intuitivelyfrom thekeyboardifthe 14 Forthose who prefer to read it in th eweb browser, theQtclass documentationcan be found on theTrolltechwebsite at ht tp://doc.trolltech.com/. 48 1.5 Qt at aGlance tabsequencemakessense.Notethatifyou do notset thesequenceyourself, Qt sets it automatically,which maynotalwaysleadtodesirable results. Figure 1.11: Thetoolsofthe Designer as multiple top-level windows In ordertouse dialogs created withDesignerinanapplicationprogram,you will need aseparat econversi on program.The Qt Designersaves thedescription of the draftversionsofaninterfaceinaseparateXML-formatted filewiththe filename extension .ui. To usethisinterfaceinaprogram,C++ code mustbecreated from theXML descriptionwiththe command-linetool uic(UserInterface Compiler ). If you useqmake to create aproject,uic can be used to integrate aDesigner-created interfaceveryeasily:Each .uifile to be used is added to theFORMSvariable byaline in the.profile.For example, thefollowinglineinthe .pro fileadds thedescription of thedialogfrommydialog.ui to theproject: FORMS +=mydialog.ui qmakethencreates acorresponding rule that generates theC++ fileui_mydialog.h from mydialog.ui,using uic. Thelatter contains theinterfacedescription of the code that implements thedialog. (Weexplainthisfile andits useinthe rest of the code for theapplicationprogram in more detail in Chapter 3onpage 91.) TheTranslation Tool “QtLinguist” Qt Linguist is used to translateapplicationprogramsfromone language to another. As aseparateGUI tool it allowsyou to integrate language translatorsinthe work processofasoftwareproject more easily.LikeQtDesigner, Qt Linguist is used in conjunction withexternalcommand-lineprograms, namelylupdateand lrelease, to updatethe binariesofasoftwareproject andreplace thewords andphrases 49 1 Basics,Tools, and First Code that aredisplayed to theuserwiththeir equivalents in adifferent language.lup- dateextractsthe texts to be localized from thesourcecode of theprogram an d generates translationfilesaccordingtoadefinition given in theproject file: TRANSLATIONS =application_fr.ts \ application_nl.ts TheGUI applicationLinguistserves as agraphical utilitywhentranslating (i.e., edit- ing) thetranslation files generated in this way(Figure1.12).Finally,lreleasecreates additionalbinaryfiles containing thetranslationsthatthe application, on request, willload at startup, andhence appear translated.Byusinglupdate, Linguist,and lrelease together in this way,the applicationcode doesnot havetoberewritten andrecompiledinorder to produce arelease that supports anotherlanguage. In orderfor allthistowork, thesourcecode of theapplicationmustfollowcertain conventions. Specifically,strings representing textthatistobetranslated mustbe passedontothe functionsQObject::tr()orQApplication::translate(). This accom- plishestwothings. It allowsQttochangestrings dynamically.Ifyou specifyonlythestring"Hello, world!" in thesourcecode,thenonlythis will be used whenthe application runs.But if you send thestringfirstthrough theQObject function tr() or to the translate()function of theQApplicationclass,thenthisfunction willlook up the translationand return astringcontainingit, which willbeusedinsteadofthe original "Hello,world!". It allowsthe lupdateutilityto look for such function calls an dthus identify passagesinthe source code that aretobetranslated. Figure 1.12: TheQtLinguist enables applications to be translatedinto other languages. 50 1.5 Qt at aGlance Unfortunately,the simple “Hello,world!” program from Section1.1 cannotbe translated into otherlanguages, sinceweusedneither tr() nortranslate()for the string "Hello,world!".Torectifythis shortcomingwereplace theline QLabel label("Hello, world!"); with QLabel label(QApplication::translate("MyLabel","Hello, world!")); Thefunction QApplication::translate()takesasthe first argument acontextlabel for thetext, whereas theQObject::tr()function theclass name of thewidgetin question is automaticallyused as thecontextlabel. 15 If, for example, you callup tr() for aQLabelobject,Qtautomaticallyuses thecontextnameQLabel. This is possible because QLabel is derived from QObject as thebaseclass andtherefore inherits thetr()function. Thecontextlabel is important because thesametextmayappearinseveral places, withdifferent meanings.Ifthe target language uses distinct terms for thesevaria- tions, theappropriate translations for theinstances of original textwill depend on thecontext. Forexample, theEnglishtextOpenmayoccurinone dialog withthe meaning openfile,but in anotherdialogwiththe meaning openInter netconnec- tion;the German version of theprogram should render thefirstinstanceasÖffnen andthe second as Aufbauen. When thetwoinstances aregiven different context labels,QtLinguistcan distinguishthem. Youshouldsendall textinyourprogram throughthe tr() or translate()function. Youwillfind that theprogram can generallybe translated without greatdifficulty whenitisdoneduringcode development, andthatitisverytedious to go through theentiresourcetextofalargeprogram byhand andadd tr() or translate()calls once thecoding is finished. Theexampleprogramsinthe remainderofthisbook thereforewilluse tr() rightfromthe beginning. (You ’ll finddetails on internationalizationand localizationinChapter 14.) Creating theProject As demonstrated in Section1.1.1,qmake creates platform-specificMakefiles from system-independent projectfiles. Therules stored in theMakefile, make,ornmake arethenusedtocompile andlinkthe application. nmake,however,onlyworks with thecommercialQtversion,not withthe opensourceedition. 16 TheGPL variant of 15 Seealsopage380. 16 TheEULAofVisualStudioisincompatible withthe GP Lanywayonce thelibrariesfromVisual Studio areincluded. 51 1 Basics,Tools, and First Code Qt 4for Windowsusesthe GCCportMinGW,which insteadofnmake provides the GNUmake knownfromLinux. qmakeproject files don’t requireustoworryabouteitherthe compilerorlinker options.For th is reason wewilluse qmakefor allthe examples in this book. In Windowsyou can also create projectfilesfor Microsoft Visual Studio withqmake, if you ownacommercialQtlicense.(TheQtintegration doesnot function in thefreevariant of Visual Studio Express; th eseusers arealsodependent on the command-line–basedversion,qmake.) Figure 1.13: Code::Blocksbuilds our“Hello,world!” program. Foropensourcedevelopers in Windows, thedevelopmentenvironment Code:: Blocks 17 provides ausefu lalternative. It works together withthe MinGWincluded in Qt, andeven hasatemplate for Qt 4projects. In orderfor it to worktogether withqmake,however,you first havetostopitfromgeneratingthe Makefileitself. To do this,selectProject→ Propertiesand mark theoptionThisisacustom Makefile. Then look for thedialogunder Project → Build options andactivatethe Commands tab. Then,inthe Pre-build stepsfield, enter thefollowingcommands: qmake -project qmake make.bat 17 Seehttp://www.codeblocks.org/. 52 1.5 Qt at aGlance To ensure that qmake is calledeven whenoth er programs(such as theQtDesigner) add newfiles,selectthe optionAlwaysexecute, even if target is up-to-date. Figure 1.13 showsCode::Blocks after the“Hello,world!” program hasbeen compiled. It is useful to storethe menu itemsfor starting theDesigner, theAssistant, or make in theToolsmenu. Youcan also usethis, to acertain extent, to quicklystartyour ownprograms, which you can specifyin thesubitem Configure tools Figure 1.14: Apple’s Xcode IDE enables efficient projectmanagement, forwhich qmake generates the necessary files. On MacOSX,the preferreddevelopmentenvironment is theXcode IDE. Apple provides this softwarefreeofchargesince OS Xversion 10.3 (Panther), butitneeds to be installedseparately.qmake on theMac convenientlycreates projectfilesfor Xcode insteadofMakefiles.However,ifyou prefer to avoidXcode andrelyon command linetoolsonly,simplyappend-spec macx-g++ to generate aMakefile: qmake-spec macx-g++ In contrast, qmake -spec macx-xcode willcause qmaketogenerateMac OS Xproject files for Xcode in allQteditions. qmakegenerates an Xcode projectfroma.pro file, which then turnsupinthe projectmanagement tool of Xcode. qmake -spec macx-g++ creates aMakefilefor direct usewithGCC. When creating yourapplicationunder Linux,the developmentenvironment KDe- velop 18 is probablythebestchoice. Version3.4 provides supportfor Qt 4projects. KDevelop includes both,aprojecttem plateand agraphical management utilityfor qmakeproject files,which can be integrated seamlesslyinto theIDE. 18 Seehttp://www.kdevelop.org/. 53 [...]... descriptions of the tools and utilities Figure 1.18: The class documentation of the QWidget class The class documentation is what is most frequently used in day-to-day work with Qt If you know the class names, you can enter them in the Index tab of the Assistant From the start page you can also access a list of all classes and a list grouped according to topics 20 For Qt 4. 1, see http://doc.trolltech.com /4. 1/... use nested layouts Figure 2. 2 shows how Qt ensures that the input fields always appear at the top of the window and that the Quit button always appears at the lower right corner of the window Figure 2. 2: How Qt layouts react to a size change in the dialog But don’t panic: Even though the source code for the constructor becomes quite long, it uses only simple functions: 65 2 The Tools Needed to Create... There are two reasons for this First, by using call-by-reference rather than call-by-value, the QString object containing the 71 2 The Tools Needed to Create Dialogs updated input to be passed to the signals/slots will not be copied when the signals and slots are invoked, and the code becomes more efficient However, use of call-by-reference allows the function to modify the actual parameter, which the. .. expression In our case, the regular expression is [ 0-9 A-Fa-f]{1 ,2} The first subexpression in square brackets specifies the characters permitted in the input string: the digits 0 to 9 and the letters A to F (written either in upper or lower case) The following subexpression, {1 ,2} , restricts the length of the input string to at least one, and at most two, characters Regular expressions in Qt are related to... Alternatively, the link List of all members, including inherited members at the beginning of the class documentation, leads to a list of all functions of the class, including inherited functions The function list is followed by a detailed description of the class In addition to a description of the tasks that the class carries out, it also explains some typical ways in which the class is used 60 Chapter 2 The. .. graphical interface and the processing logic for the application: If the user changes the value in one of the line-edit widgets, the ByteConverterDialog class calls the corresponding slot, which adjusts the value of the two other line edits Figure 2. 5 depicts this Such a dovetailing of the GUI and the application logic brings the risk of a program design that is confusing and difficult to maintain If,... management, so that the validator will be deallocated when the widget is The setValidator() call then causes the validator to keep an eye on the input given to the object pointed to by decEdit Now the user can type only whole numbers between 0 and 25 5 in the input field To check the validity of hexadecimal numbers, we must make use of another type of validator: QRegExpValidator This compares the input, viewed... sets up all the necessary signal/slot connections The entire logic of the application is contained in the code for slots and in their connections to the corresponding signals 2. 2 Separation of GUI and Processing Logic 2. 2.1 Alternative Design In the previous example program, we defined a single ByteConverterDialog class that implements both the graphical interface and the processing logic for the application:... as expected and synchronize the three input fields with one another To ensure that clicking the Quit button will close the byte-converter dialog, we extend the ByteConverterDialog constructor to associate the clicked() signal of the 70 2. 1 What’s the Difference Between Dialogs and Widgets? button with the accept() slot of the dialog The slot is provided by QDialog, which the ByteConverterDialog class... to the signals and slots of the ByteConverter class, for example, the hexChanged() signal of the decEdit object in a dialog to the setDec() slot of the associated ByteConverter If the user enters a new decimal value, the line-edit widget sends out the textChanged() signal and setDec() is applied This slot in turn sends out the signals hexChanged() and binChanged() Since we have connected them to the . withQHttp andQFtp. UnlikeQtGui,QtNetworkrequiresthe QtCorelibrary,but it can,ofcourse, be used together withQtGui andthe otherlibraries. TheOpenGLLibraryQtOpenGL TheQtOpenGL libraryenablesOpenGLtobeusedinaQt program.Itprovides the QGLWidgetclass—aQtwidgetinwhich. withthe Qt 3versions, andothershavebeen replaced in Qt 4withcompletelynewclasseswithdifferent names. In ordertosimplifytheporting of Qt 3programstoQt4,Trolltechincludes thecorresponding Qt 3classesinthe. andQBrush Classesprovidingready-to-usedialogs (including QFileDialog andQPrintDialog) TheQApplicationclass QtGui requires theQtCorelibrary. TheNetworkLibraryQtNetwork Thepartial libraryQtNetworkprovides classesfor

Ngày đăng: 13/08/2014, 08:21

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan