外文翻译 - Qt4图形设计与嵌入式开发_第1页
外文翻译 - Qt4图形设计与嵌入式开发_第2页
外文翻译 - Qt4图形设计与嵌入式开发_第3页
外文翻译 - Qt4图形设计与嵌入式开发_第4页
外文翻译 - Qt4图形设计与嵌入式开发_第5页
已阅读5页,还剩10页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

0外文原文Qt4graphicdesignandembeddeddevelopmentHuangLiqin,DingLinsong.Qt4graphicdesignandsoftwaredevelopmentofM.peoplespostandTelecommunicationsPress,2009Chapter1GettingStartedQtineachclass,thereisacorrespondingheaderfilewiththesamename,whichcontainstheclassdefinition.Forexample,touseQApplicationclass,youwillneedtoaddedintheprogram#includeQApplicationclassusedtomanageresourceswithinthescopeofapplication.Itsconstructortoargcandargvasparametersofthemainfunction.Isnotvisiblewhenthewidgetiscreated(alwayscreatedhidden).Canaccommodateotherwidgetsinthewidget.InQtwidgetsintheuserbehaviororstatechangewillemitsignal.Signalcanbeconnectedtogetherandslotfunction(connect),sothatwhenasignalisemit,thecorrespondingslotfunctionwillautomaticallybeinvoked.QWidgetclassconstructorneedsaQWidget*pointerastheargument,saiditsparentwidget(thedefaultvalueis0,thereisnoparentwidget).Intheparentwidgetisdeleted,Qtwillautomaticallydeleteallofitschildwidgets.TherearethreekindsofLayoutinQtManagerclasses:QHBoxLayout,QVBoxLayout,QGridLayout.BasicmodeisaddwidgetsintheLayout,theLayoutautomaticallyoverthesizeandpositionofthewidget.StarttheQtapplicationcanpass-styleparameterschangethedefaultexplicitstyleoftheprogram.Chapter2CreatingDialogs2.1SubclassingDialogThebaseclassforalldialoginQtisQDialog.QDialogderivedfromQWidget.AllthedefinesasignaloraslotintheQtclass,atthebeginningoftheclassdefinitionmustusetheQ_OBJECTmacro.Qtsignalofkeywordsisactuallyamacrodefinition.Similarly,slotskeywordisalsoamacrodefinition.Classisdividedintoseveralmodules:providedbyQtQtGui,QtNetWork,QtOpenGL,QtSql,QtSvgandQtXml,etc.QObject:tr()functionconvertstheinputstringtootherlanguages(international).Visibletoallusersofthestringisusedbythetr()functionisagoodhabit.Buddy:AandBtwowidgets,ifhaveAshortcutkey,whentheuserpressestheshortcutkey,programinputfocusautomaticallytransfertoB,saysthatBisABuddy.QWidget:close()isaslot,thedefaultbehavioristomakethecorrespondingwidgethidenotvisible,butdonotdeletethewidget.CanbeincludedintheLayoutwidgetsandotherLayout.ByusingnestedQHBoxLayoutMOC(Meta-Object-theCompiler):usedforalltheQ_OBJECTmacroclass,allneedthroughtheMOCprocessatcompiletime,otherwisetherewillbealinkerror.Asolutiontotheerrorisalsoverysimple,toperformqmaketoupdatethemakefile,andrecompile.12.2SignalandSlotintheDepthSignalandSlotmechanismisthefoundationofQt.Slotandordinaryc+classmemberfunctionalmostthesame;Maybevirtual,canbeoverloaded,canbepublic,protected,orprivate,andalsocanbesocalleddirectlybyothermemberfunctions.Thelinkbetweenthesignalandslotcanbeone-to-one,one-to-manyormoreonone.Betweenthesignalandthesignalcanalsobeassociated,thesituationandthedifferencebetweensignal-slot,whenthefirstMr.Sigalemitthesecondsignalisalsoemit.Cancalldisconnect()toremovethelinkbetweenthesignalandslot,usuallyrarelyneedtoexplicitlycalldisconnect(),becausetheobjectisdeletedwhentheQtwillautomaticallyremovetherelevantassociation.Mr.Sigal-slotorsignal-signal,thisconnectionrequiresbothhavethesameparameterlist;Ifthesignalismorethantheparametersintheslot,theextraparameterisignored.Mind-set:signal-slotmechanismcanonlybeusedforthewidget.Infactsignal/slotmechanismisimplementedbytheQObject,isnotconfinedtoGUIprogramming,canbeusedforanyQObjectsubclass.2.3RapidDialogDesignUsetheQtDesignercreateformeventuallybeconvertedtoc+code.Qmaketoolcandetectinterfacefile(*.TheUIfiles),andcalltheuic,namelyQtuserinterfacecompiler.Uic.Theuserinterface(UI)fileisconvertedtothec+code,inaformforui_xxx.Hfile.Thefiledialogisgiventhecorrespondingcompletedefinitionofaclass,andcontainsasetupUi()memberfunction,isusedtoinitializetheform.NotethatthisclassisnotcreatedbyuicisderivedfromanyQtclass.Qtparent-childmechanismarerealizedbytheQObject.Whencreatinganobjectifitspecifiestheparent,theparentwillbetheobjecttoaddtotheirchildernlist.Whentheparentisdeleted,Qtwilltraversethechildernlistanddeleteeachchild,theprocesswillberecursive.Thissystemgreatlysimplifiesthememorymanagement,reducetheriskofmemoryleaks,programmersneedtoexplicitlydeletedbynewcreatedandnottheparentobject.Forthewidget,theparentandanadditionallayerofmeaning:thechildwidgetisdisplayedintheparentwithinthescopeofthewidget.Ifyouremovetheparentwidget,notonlythechildwidgetisreleasedfromthememory,willdisappearonthescreen.QDialog:theaccept()willreturntoavalueofdialogfortheQDialog:Accepted(avalueof1),andQDialog:reject()returnsavalueQDialog:Rejected(avalueof0).2.4theDynamicDialogsTheDynamicDialogatruntimebasedonreferstotheprocess.TheUIfilecreationDialog.Thisdialogwillnotbyuic.UIisconvertedtothec+code,butatruntimeusingQUiLoaderclassloading.TheUIfiles.CanuseQObject:findChild()toaccesstheformofchildwidgets.TouseQUiLoader,needinQtprogram.Profileaddthefollowingcontent:TheCONFIG+=uitoolsDynamicdialogallowstherecompiletheprogramunderthepremiseofnotchangethelayoutoftheform.Chapter3,CreatingtheMainWindows3.1SubclassingQMainWindowTheapplicationsmainwindowisaccomplishedbycreatingaQMainWindowderived2class.QMainWindowandQDialog,areallderivedfromQWidget.CloseEvent()isavirtualfunctionprovidedbytheQWidget,whentheuserclosesthewindowwillautomaticallybeinvoked.SetCentralWidget()toaWidgetsetmainwindowscentralWidget,whilethecentralWidgetmeansinthemiddleofthedisplaywilloccupythemainwindowposition.QtGUIprogrammingsupportunderavarietyofgraphicalformat.Canuseavarietyofwaysfortheapplicationtoprovideimages,oneofthemostcommoninclude:1).Theimageisstoredinthefile,theruntimeloads.2.)insourceincludeXPMfile(XPMfileitislawfultoc+).3).TheuseoftheresourcesofQtmechanism.Qtresourcemechanismismoreconvenientthantheruntimeofloading,andforallsupportedimageformatscanbegoodwork.InordertoexploittheresourcesofQtmechanism,youneedtocreatearesourcefile,andin.Profilecorrespondingtoaddalinetoresourcefilesareidentified.Suchas:RESOURCES=spreadsheet.QRCResourcefileitselfusingasimpleXMLformat.Itiscompiledintotheexecutablefile,sowillnotbelost.Infixingtheresources,theuseofpathprefix:/,forexample:/images/iconPNG.Canbeanytypeofdocumentresourceitself.3.2CreatingMenusandToolbarsTheconceptofQtbyintroducingtheActionsimplifiestheprogrammingofthemenuandthetoolbar.AnActioncanbeaddedtoanynumberofmenuandtoobar.OnthemenuandtoolbarinQtprogramminginvolvesthreesteps:1.)createandsetuptheAction2).Tocreatethemenu,andaddtheAction3).Tocreatethetoolbar,andaddtheActionActioniscreatedbyQActionclass,foreveryAction,canbesetfortheaccelerator,theparent,theshortcutkey,visibilityandstatustipandotherproperties,andcancalltheconnect()fortheActionistriggeredtoperformoperations.QTableWidgetbaseclassQAbstraceItemViewprovidesselectAll()theslot.QApplicationclassprovidesaboutQt()thisslot,canuseglobalvariablesqApp(atypeofQApplication*pointer)touseit.InQt,menubyQMenuinstancesoftheclass.WhichistobeplacedinQMenuBarQmenu.FunctionQMainWindow:menuBar()returnsapointertypeisQMenuBar*.QMenuBar:addMenu()accordingtothespecifiedtexttocreateaQMenuwidgetandadditintotheMenuBar.QMenu:addAction()toaddtheActionMenu.HaveanyQtwidgetscanberelevantinaseriesofQAction.BycallingtheQWidget:addAction(),canaddtheActionfortheWidget.Thisfeaturecanbeusedtocreatethecontextmenu.3.3SettingUptheStatusBarQMainWindow:statusBar()returnsapointertothestatusbar.ThestatusbarinthestatusBar()isinvokediscreatedforthefirsttime.33.4ImplementingTheMenuQMessageBox:DefalutmodifierhasbeenmodifiedButtonbethedefaultButton,theQMessage:EscapemodifierismadetheEsckeytriggerautomaticallymodifyButton.QMessageBox:warning()isusedforpopupsdialogbox.ThefunctionaspartoftheQtprovidesstaticconvenicencefunction.QFileDialog:getOpenFileName()canbeusedtomakeafilenamefromtheuser-thisfunctiondisplaysafileselectiondialogboxthataskstheusertoselectafile,andreturnsthefilename,orwhentheusertoselectCancelreturnsanemptystring.Thefunctionofthefirstparameteristheparentwidget.Fordialogandotherwidgets,theparent-childrelationshipmeansthatitisnotexactlythesame.Adialogisalwaysaseparatewindow,butifithasaparent,thedefaultcenteredovertheparentshow.Whentheuserclosesthewindowoftheoperation,Qwidget:close()theslotwillbecalled,theslotsendclosetothecorrespondingwidgetevent.ReimplementQWidget:closeEvent()tointercepttheevent,todeterminewhetherreallywanttoclosethewindow,topreventwrongoperation.EachQWidgethasawindowModifiedattribute,thewindowshouldbesettoTrue,whenweamendthedocumentisotherwiseissettofalse.QString:arg()functionisthelowestnumberinthestring%nreplacewithparameters,andreturnsthereplacementstring.EachActioncanhaveoneforQVarianttypeofassociateddata.IntheQtqobject_cast()mechanismfordynamiclibrariescanworknormally.3.5UsingtheDialogModelesswindow-onethatrunsindependentlyofanyotherWindowsintheapplicationFormodelessdialog,whenitsejection,maybeinthreeconditions:1).Thisisthefirsttimethatthedialogisactivated2)beforethedialoghasbeenactivated,buttheusertoshutitdownagain3)beforethedialoghasbeenactivated,andisstillvisibleShow()willbeahiddenwindowbecomesvisible,andactivateWIndow()willbestateofthewindowbecomesactive.Themodelwindow-remobilisedupwheninvokedandblockstheapplication,preventinganyotherprocessingorinteractionsuntilitisclosed.Ifadialogwiththeshow()toactivate,ismodelessdialog;Ifthroughtheexec()toactivate,itisthemodeldialog.Inaddition,youcancallsetModel()todisplaymodeSettingsdialog.QDialog:exec()returnstowhenthedialogisconfirmedastrue,falseotherwise.Createdonthestackmodeldialogisagoodprogrammingpractice,becauseafterusingnolongerneed,andthemodeldialogwillautomaticallybedestroyedattheendofthescope.BecausemostoftheapplicationoftheAboutboxarehighlysimilar,QtprovidesaconvenientinstaticconvenicencefunctionQMessage:About(),thefunctionandQMessageBox:warningissimilar().3.6StoringSettingQtisthroughQSettingsclasstosettheapplicationspositionrelatedinformationstoredintheplatform,Windowsintheregistry,existintheUnixtextfile.QSettingsconstructorcontainstwoparameters,respectivelyistheorganizationsnameandtheapplicationsname,QtUSESthesetwoparameterstopositiontheapplicationSettingsinformation.4QSettingsinformationstoredintheformofthekey-valuepair.3.7MultipleDocumentsTorealizethedocs,youmustwanttocreatethemainwindow,throughnewontheheapratherthanonthestacktocreatethemainwindow.QAplication:closeAllWindows()theslottocompletealloperationistoclosetheapplicationwindow,unlessonewindowrefusedtoclosetheevent.Programmersdontneedtoworryaboutunsavedchanges,whichbyQWidget:closeEvent()isresponsibleforprocessing.ThroughtheMainWindowconstructorinvokesthesetAttribute()functiontosettheQt:WA_DeleteOnCloseproperties,canasktheQtitautomaticallydestroyedwhenthewindowisclose.QtinitsavailableonallplatformssupportthecreationofSDIandMDIprogram.3.8SplashScrennsFortheprogramtoaddintheQtsplashscreenisverysimpleandcanbedonebyQSplashScreenclass.Normally,andthesplashscreenrelatedcodeinthemain(),inthecallQApplication:exec()before.ChapterfourImplementingApplicationFunctionalityChapter4ImplementingApplicationFunctionality4.1TheCentralWidgetQMainWindowcentralregioncanbeanytypeofwidget.4.2SubclassingQTableWidgetQTableWidgetautomaticallycreatesQTableWidgetItemtostoretheuserinput.QTableWidgetItemclassisnotawidget,butapuredataclass.QTabeWidget:setItermProtype()canbesetinthecaseofuserinputtoautomaticallycreatewhatkindofclass.4.3LoadingandSavingQFile&QDataStreamQFiledestructorsareresponsibleforwillopenfileclosed.QDataStreamclasshasastronggeneralityandcanbeappliedtoQFile,QBuffer,QProcess,QTcpSocket,QUdpSocket.QtalsooffersaQTextStreamclassisusedtoreadandwritetextfiles.4.4SubclassingQTableWidgetItemSeveraldatacanbestoredineachQTableWidgetIterm,thisisdonebyaQVariant.EveryQVariantobjectstostoreonekindofdatainacertainrole,commonlyusedroleshaveQt:EditRoleandQt:DiaplayRole.QVarinantobjectcanholdmultipletypesofvariablevalues,andprovidetoothertypesoftransformationfunctioninterface.UsethedefaultconstructorcreatesQVariantobjectsisconsideredinvalidvariant.Chapter5.CreatingCustomWidgets5CustomusercontrolscanberealizedthroughinheritanceexistingQtcontrol,alsocanbedonedirectlyinheritedfromQWidget.5.1SubclassingQWidgetThroughthestudyofthederivationofQWidgetandrewritesomeofitseventhandlerforthedrawingandresponsetoauseraction,programmerscanimplementcompletecontrolovertheappearanceandbehaviorofthewidget.Qtsbuilt-inwidgetssuchasQLabel,QPushButton,QTabelWidget,etc.,inthisway.MacroQ_PROPERTY()isusedtoforthewidgetdeclarationandaddcustomproperties.Thedefinitionofeachattributecorrespondstoadatatype(anytypecanbesupportedbyQVarinat),areadfunctionandoptionalwritefunction.Forclasscontainsthecustomattributes,Q_OBJECTandQ_PROPERTY()thetwomacrosareessential.QImageclassstoredimageinformationintheformofahardwarehasnothingtodo.Qtprovidestwotypesusedtostorethecolourinformation:QRgbandQColor.QRgbisactuallyatypedef,32-bitpixelstoholdinformation.QColorisaclassprovidesanumberofinterfacefunction,widelyusedtostorethecolorintheQt.QWidget:update()functionisusedtotomandatoryredrawthewidget.QWidget:updateGeometry()isusedtoinformcontainsthewidgetLayout:thesizeofthewidgethinthaschanged,toadjusttheLayoutautomatically.BycallingtheQWidget:update()andQWidget:repaint(),canbemandatorytoproduceapaintevent,butdontlieinbothrepaint()leadtoredrawimmediately,andtheupdate()onlytoapainteventintotheeventqueue.Ifcontinuousmultiplecallstotheupdate(),andQtwillcontinuouspainteventcompressedintoapaintevent,inordertopreventtheimagedithering.Eachwidgethasapalette,isusedtosetthewidgetunderwhatcircumstancesusewhatcolor,suchasthebackgroundcolor,text,etc.Thewidgetpaletteiscomposedofthreecolorgroup:activeandinactive,disabled.QWidget:thepalette()returnsthewidgetpalette,intheformofQPalettewhileclolorgroupbyenumerationtypeQPalette:ColorGroupspecified.5.2IntergratingtheCustomWidgetswithQtDesignerLiketheuseofacustomwidget,inQtDesignermustlettheQtDesignercanknowoftheirexistence.Therearetwokindsofmechanisms:promotionapproach&pluginapproachPromotionapproachisalsoveryeasilytosavetime,butthedisadvantageisthatthecustomwidgetofcustomattributesarenotvisibleintheQtDesignerandnottoaccess,andusethepluginapproachwhentherearenosuchproblems.PluginapproachforcreatingaQtDesignercanbeloadedatruntimethepluginlibrary,tocreatethewidgetinstance.DuetotheMOCmechanismQt,QtDesignercandynamicallyobtainthewidgetpropertylist.InordertousethepluginthattoQDesignCustomWidgetInterfacederivedinthefirstplace,andwritesomevirtualfunctions.Q_INTERFACES()macroisusedtoinformQtthisclasswhichimplementstheinterface.Tailinrealizingthepluginclassofsourcefiles,youmustusetheQ_EXPORT_PLUGIN2()macroallowstheplugintoQtDesignerisvisibleandavailable.Thefirstparametertothemacroisthenameofthe6plugin,andthesecondparameteristheclassnameoftheplugin.5.3DoubletheBufferingQWidget:style()returnsfordrawingstyleusedbythewidget.QtisthestyleintheQStylederivedclass.Inthesameapplicationwidgetsaregenerallyusethesamestyle,butyoucancallQWidget:setStyle()forspecialwidgetlevelSettings.Chatper6LayoutManagement6.1LayingOutWidgetsonaFormQtprovidesthebasicLayoutManagerinclude:QHBoxLayout,QVBoxLayout,QGridLayoutandQStackLayout.OthertocompleteLayoutinQtclassesincludingQSplittermanagementfunction,QScrollArea,QMainWindowandQWorkspace.QtmanagementofchildwidgetstheLayoutofatotalofthreeways:absolutepositioning,manualLayoutandLayoutmanagers.Absolutepositioning:namelybytheprogrammerthroughhard-codedchildwidgetsintheformofamanagementpositionandsize.ThelocationoftheManualLayout:thechildwidgetisdeterminedbymeansofhard-codedbytheprogrammer,butthesizeandthesizeoftheparentwindowwithacertainproportion,ratherthancompletelyhard-coded.ThiswayofformresizeEvent()functionthepositioningofthechildwidgetto.IsthemostimportantthreeLayoutmanagerQHBoxLayout,QVBoxLayout,QGridLayout,theyareallderivedfromQLayoutQGridLayoutuseslightlycomplicated,itworksinatwo-dimensionalgridofcells.TheQGridLayout,toaddthewidgetasfollows:Layout-addWidget(widgets,row,colom,rowSpancolumnSpan)Thewidgettobeaddedtothechildwidgets,rowandclomundeterminethewidgetoccupiedthespaceintheupperleftcorneroftheCelllocationcoordinates,androwSpancolumnSpanistospecifythesizeofthewidget,thesetwoparametersofthedefaultvalueis1.AddStretch()totheLayoutManagertoaddplaceholder.Thesizeofeachwidgethasitsownpolicy,byitstoldhowtodealwiththewidgetLayoutsystemshapeastretchorshrink.QtwidgetsinthesizeofthepolicyisrepresentedbyQSizePolicyclass.EachQSizePolicyfromhorizontalandverticaltwogroupsthesizeofthepolicy,themostcommonvaluesinclude:FixedMinimumMaximumPreferedExpandingInadditiontotheabovetwogroupsthesizepolicy,QSizePolicystillstoredinthehorizontalandverticaldirectionthestretchfactor,thevalueisusedtoshowthatwhentheformsizeextensionwidgetscaleratio.6.2StackedLayoutsQStackLayoutclasstomanagemorethanonepage,buteachtimetheshowonlyoneofthem,andhidotherpagetotheuser.QStackLayoutclassitselfisnotvisible.Forconvenience,areincludedintheQtQStackedWidgetclass,thatis,abuilt-inQStackedLayoutQWidget.76.3theSplitterClassQSplitterisawidgetcancontainotherwidgets.QSplitterwidgetscontainedinorder,andsplitterhandleseparatedfromeachother.QSplittertodeterminebytheparametersintheconstructorishorizontalorverticaldirection.IsdifferentfromthefronttointroducetheLayoutoftheMangenerisresponsibleforhandlingthewidgetLayoutandwithouttheirownvisualization,saidQSplitterisderivedfromQWidget,soitcanbeusedwithotherwidgets.QSplitterclassprovidesthestoragestatusoftwofunctions:saveState()andrestoreState().6.4ScrollingAreasQScrollAreaclassprovidesamovableviewportand2sliders.QScrollAreausedmethodistocallitssetWidget()function,willwanttoaddthesliderwidgetisadded.QScrollAreaautomaticallyaddedthewidgetsettheparentastheviewport,andtheirownviewpointthroughQScrollArea:viewport()foravisit.QScrollAreamostfunctionisacquiredthroughinheritanceQAbstraceScrollAreaclass.AndsuchasQTextEditandQAbstractIterViewclassisderivedfromQAbstractScrollArea,sothereisnoneedtobewrappedhiminQScrollAreaclasstotakeadvantageofthescrollbar.6.5theDockWidgetsandToolbarsInQt,thedockwidgetisdonebyQDockWidgetclass.Eachofthedockwidgethasitsowntitlebar.StartfromQt4,thetoolbarhastheirowndisplayspace,andisnolongerasinthepreviousversionallowsthedockwidgettoshare.CallstoawidgetsetAllowedArea()canbespecifiedtoallowinthedockareasplacedonthewidget.6.6MultipleDocumentInterfaceQt,writeMDIprogramisthroughtheuseofQWork

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论