外文翻译 -先进的Qt编程_第1页
外文翻译 -先进的Qt编程_第2页
外文翻译 -先进的Qt编程_第3页
外文翻译 -先进的Qt编程_第4页
外文翻译 -先进的Qt编程_第5页
已阅读5页,还剩12页未读 继续免费阅读

下载本文档

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

文档简介

0外文原文AdvancedQtProgrammingTheapparentubiquityofthe“computingcloud”,thereadyavailabilityofwebenabledmobilephonesandsmallform-factornetbookandsmartbookcomputersnottomentiontheGoogleDocsfilestoreandthezero-deploymentcostsofweb-basedapplicationsmightleadustobelievethatdesktopapplicationsaredinosaursthatdontyetknowtheyreextinct.ButbeforeweabandonC+andQtandswitchtowebprogrammingandthesubtlepleasuresofJavaScriptandHTML,itisworthreflectingonjustsomeoftheadvantagesthatdesktopapplicationscanprovide.Ideallywewouldliketohaveallthebenefitsofdesktopapplications,andatthesametimeenjoyalltheadvantagesofInternetaccesswhenitisavailable.ThankstoQtsQtWebKitmodule,introducedwithQt4.4,thiscanbeachieved,sinceQtWebKitallowsustocreatehybriddesktop/Internetapplicationsthatcanworkbothofflineandonline.Themaindisadvantagecomparedwithweb-basedapplicationsisintheareaofdeploymenttheQtapplicationmustbeavailableontheuserscomputer.Incaseswherethedeploymenteffortorbandwidthutilizationmustbeminimizedthereareseveralapproachesthatcanbetaken.Forexample,wecanputalotofapplicationfunctionalityintorelativelysmallpluginsthatcanbeupdatedindependently.OrwecoulduseapplicationscriptingtoprovidemuchoftheapplicationsfunctionalityusingtheQtScriptmoduleforJavaScript(ECMAScript)orathird-partymoduleifwewanttouseadifferentscriptinglanguageandjustupdateoraddindividualscriptsasnecessary.Orwecouldputasmuchfunctionalityaspossibleintotheserverandintowebpagescripts,therebygreatlyreducingthenumberoftimesweneedtoupdatetheclient.InthischapterwewillfocusonkeyaspectsofQtssupportforhybridapplications.InthefirstsectionwewillusetheconvenientQNetworkAccessManagerclassintroducedinQt4.4,tocreateInternet-awarewidgets.InthesecondsectionwewillmakeuseoftheQtWebKit1module,startingbydevelopingagenericwebbrowsercomponentasurprisinglyeasytaskthankstothefunctionalityprovidedbytheQtWebKitmodule.Wewillthenmakeuseofthegenericwebbrowsercomponentforexample,tocreateawebsite-specificapplicationandusetheQtWebKitmoduletoaccesstheDOM(DocumentObjectModel)ofwebpagesdownloadedbehindthescenessothatwecanextractinformationfromthemforfurtherprocessing.AndthenwewillseehowtoembedQtwidgetsincludingourowncustomwidgetsintowebpages,toprovidefunctionalitythatisnotavailableusingthestandardHTMLwidgets.OurdefinitionofanInternet-awarewidgetisawidgetthatautomaticallyretrievesdatafromtheInternet,eitherasaone-offeventwhenitisconstructed,oratregularintervals.TheeasiestwaytocreateanInternet-awarewidgetistocreateawidgetsubclassthatmakesuseofaQNetworkAccessManagerobject.TheseobjectsarecapableofperformingHTTP(andHTTPS)HEAD,POST,GET,andPUTrequests,andalsoofhandlingcookies(usingQNetworkCookieJar)andauthentication(usingQAuthenticator).InthissectionwewilllookatanexamplethatusesoneQNetworkAccessManagertoreaddatafromtheInternetattimedintervals,andanotherQNetworkAccess-Managerthatisusedtodownloadimagesondemand.ThisshouldbesufficienttogiveaflavorofhowQNetworkAccessManagersareused.Figure1.1illustratestherelationshipbetweenaQNetworkAccessManagerandanexternalwebsite.NotethatsinceQNetworkAccessManagerispartofQtsQtNetworkmodule,anyapplicationthatusesitmustincludethelineQT+=file.Thissectionsexampleisataskbartrayiconapplication.Suchapplicationsaretypicallyusedforfrequentlyusedcontrolssuchasvolumecontrols,ortoprovidestatusinformationsuchasmemoryusageorthecurrentdateandtime.Inthissectionwewilldevelopthe2WeatherTrayIconapplication(weathertrayicon).ThisapplicationshowsaniconcorrespondingtothecurrentweatherconditionsataspecifiedU.S.airportwithboththeiconandthedataretrievedfromtheU.S.NationalWeatherService().Figure1.2sleft-handscreenshotshowstheWeatherTrayIconapplicationandatooltiptheiconisunderthebottom-rightcornerofthetooltip.Thefiguresright-handscreenshotshowstheapplicationscontextmenu.Onceanhourtheapplicationdownloadstheweatherdataandthecorrespondingiconforthechosenairportsweatherconditionsandupdatesitselfaccordingly.TaskbartrayiconapplicationslikethisworkonallofQtssupporteddesktopplatforms.Forexample,thescreenshotsinFigure1.2weretakenonLinuxrunningFedorawiththeGNOMEdesktop.OnWindowsandMacOSXthetooltipwouldbeplaintextsinceQttooltipsonthoseplatformsdontsupportQtrichtext(HTML);andofcourseonMacOSXtheiconappearsinthemenubaraswewouldexpect.Whenreviewingmostofthebooksexampleswewontusuallyshowthemain()functionsbecausetheyarealmostallsimpleandstandard.Butinthiscasethereareacoupleofimportantdeviationsfromthenorm,sowewillshowtheWeatherTrayIconapplicationsmain()function.ThefunctionstartsinthestandardQtwaywiththecreationofaQApplicationobject.Wesettheapplicationsname,whichwecanlateruseforexample,fordialogtitlesaccessingitwithQApplication:applicationName(),andwealsosettheorganizationsname3anddomainwhichmeansthatwecancreateQSettingsobjectswheneverwewantwithouthavingtobothergivingthemanyarguments.Therearetwounusualaspectstothisfunction.ThefirstisthatwehavetoldQtnottoclosetheapplicationwhenthelastwindowisclosed.Thisisbecausenormallyatrayiconapplicationhasnowindow(itjusthasatrayicon),andanywindowsitdoesusearenormallytransient(e.g.,atooltiporacontextmenu),andtheirclosureshouldnotimplicitlycauseapplicationtermination.ThesecondunusualaspectisthecalltoacustomenableNetworkProxying()function.Thisfunctionisdiscussedinthe“SupportingNetworkProxying”sidebar.Ifthefunctionreturnsanonzeroerrorcodeitsignifiesthatanerroroccurredinwhichcasewereturntheerrorcodeandterminatetheapplication.Theweatherdataisprovidedinvariousformats,butwehavechosentoaccessitinXMLformat.Theformatitselfisverysimple,consistingessentiallyofalistofkeyvaluepairswherethekeyisatagnameandthevalueisthetextbetweentheopeningandclosingtags.Forexample:Whentheapplicationfirststartsitsetsitsairporttotheonethatwaslastsetbytheuser,ortoadefaultairportthefirsttimeitisrun.ItthenusesaQNetwork-AccessManagertoretrievetheweatherdata.TwoelementsofthedataareaURLandafilenameforaniconthatcorrespondstotheprevailingweatherconditionsattheairport.TheapplicationusesasecondQNetworkAccessManagertoretrievetheiconandsetsthisastheiconshowninthetaskbartray.Infact,theapplicationcachesiconstoeconomizeonbandwidth,aswewillseeshortly.Wewillshowandexplainallthemethodsinamomentincludingtheprivateonesnotshownbutnowwellcommentonsomeoftheprivatememberdata.4Theairportstringholdsthecurrentairport,forexample,“Chicago/Ohare(KORD)”.TheiconCachehasQUrlkeysandpointerstoQIconvalues.Wewillcovertheotherswhenwediscussthemethodstheyareusedin.TheQCacheclasscachesitemsusinga“cost”scheme.Thecachesmaximumcostdefaultsto100thesumofitemcostsisalwayslessthanorequaltothemaximum.Bydefaulteachitemhasacostof1,sounlesswechangethemaximumorsetourownitemcoststhecachewillholdupto100items.Whenanewitemisadded,iftheitemscostmakesthesumofcostsexceedthemaximumcost,oneormoreoftheleastrecentlyaccesseditemsareremoveduntilthesumofcostsislessthanorequaltothemaximum.BehindthescenesQCacheusesaQHashtoprovideveryfastlookupbykey.However,outofthebox,QHashcannotstoreQUrlsaskeysbecauseQtdoesnotprovideaqHash(QUrl)function.Thisiseasytoremedywithaone-liner:inlineuintqHash(constQUrlHerewevesimplypassedtheworkontothebuilt-inqHash(QString)function.Wearenowreadytoreviewthemethods,startingwiththeconstructor.Wegivetheapplicationaninitialicontousewhilewaitingforthefirstweathericontobedownloaded.Thenwecreateacontextmenuwithactionsforchangingtheairportandforterminatingtheapplication.MostoftheconstructorisdevotedtosettinguptheInternetaccessbycreatingtwoQNetworkAccessManagers.Oneisusedtofetchtheweatherdataandtheothertofetchtheiconassociatedwiththecurrentweatherconditions.Weuseseparatenetworkaccessmanagerssothattheycanworkindependentlyofeachother,andinbothcaseswecreateasinglesignalslotconnectionsinceallweareinterestediniswheneachdownloadisfinished.Finally,wecalltherequestXml()slotusingasingleshottimer.ThismethodmakesuseofthenetworkXmlAccessnetworkaccessmanagertofetchtheweatherdataforthecurrentairport.WecouldhavesimplycalledrequestXml()directly,butasamatterofstyleweprefertorestrictourselvestocalling“create”methodsthatcontributetotheconstructionofanobjectinconstructors,andtocallanypost-constructioninitializingmethodusingasingleshottimer.5Thisensuresthatbythetimetheinitializingmethodiscalled,theobjectisfullyconstructed.Thismeansthattheinitializingmethodcanaccessanymembervariableormethodsomethingthatisnotguaranteedtobesafeduringconstruction.BeforewelookattherequestXml()slot,wellbrieflylookathowthecontextmenuiscreated,toseehowtheairportwhosedetailsmustbedownloadedcanbesetbytheuser.Herewehaveusedahard-codedlistofairportnames,butwecouldjustaseasilyhavereadthemfromafileorresource.(IfwewantedtolistalltheU.S.airportswecouldeasilygroupthemforexample,byhavingstatesastop-levelmenuitems,andairportsassubmenuitems.)WeuseQSettingstosetthecurrentairport,defaultingtothefirstoneinthelistthefirsttimetheapplicationisrun.ForeachairportwecreateaQActionandchecktheonethatmatchesthecurrentairport.EachairportactionisaddedtoaQActionGroup.BydefaultaQActionGrouphasitsexclusivepropertysettotrue;thisensuresthatitsactionshaveradiobuttonratherthancheckboxcheckmarksandthatonlyoneairportisevercheckedatanyonetime.Wealsoaddanexitactionandgiveitaspecifickeyboardaccelerator.ThenwecallAQP:accelerateMenu()toprovidekeyboardacceleratorsforasmanyairportsaspossible,andthensetthemenuwehavecreatedastheapplicationscontextmenu.IftheapplicationisbeingbuiltonMacOSXthecalltoAQP:accelerateMenu()normallyhasnoeffect,sinceMacOSXdoesntsupportaccelerators.Seethe“KeyboardAccelerators”sidebarformoreaboutautomaticallysettingkeyboardaccelerators.WeneedtoconnecteachactionwiththesetAirport()slotandtoparameterizeeachslotinvocationinsomewaysothattheslotknowswhichairporthasbeenchosen.AneasywaytodothisistocallQObject:sender()insidetheslottoseewhichactioncalledit,andthentoextracttheactionstexttodeterminethechosenairport.AnalternativeistouseaQSignalMapper.ButinthiscasethereisaneveneasiersolutioninsteadofconnectingeachoftheairportQActionsweconnecttheQActionGroupinstead.TheQActionGroup:triggered()signalcarriestherelevantQActionasitsparameter.6TheXMLweatherdataforagivenairportisinafilewhosenamematchestheairportsfourlettercode.Wehaveincludedthiscodeinparenthesesattheendofeachairportsname,andusebasicQStringmethodstoextractit.OncewehavetheURLweneedweusetheXMLnetworkaccessmanagertodoaGETrequestonit.WhenarequestismadeapointertotheQNetworkReplyobjectthatwillreceivetheresultsisreturned.Theseobjectsemitsignalsindicatingprogress,forexample,downloadProgress()anduploadProgress(),andwhentherequestfinishes,thereplyobjectissuesafinished()signal.Thenetworkmanagerthatinitiatedtherequestalsoemitsafinished()signal,andsincewearenotconcernedwithmonitoringprogressthisistheonlysignalweconnectedtoandthereasonwhyweignoredtheQNetworkAccessManager:get()methodsreturnvalue.Oncethedownloadisfinished(successfullyornot),thesignalslotconnectionshownearlierensuresthatthereadXml()methodiscalledwithapointertothereplyobjectasitssoleargument.Iftherequestfailedweputtheerrormessageinthetrayiconstooltipandtryagainlaterafteradelay.ThedelayisheldintheprivateretryDelaySecvariableandisinitializedto1.(Wemustmultiplyby1000becauseQTimer:singleShot()takesatimeoutinmilliseconds.)Oneachsuccessivefailurewedoublethedelayintervalleftshiftinganintegerbyonebitdoublesitsvalue.Soafterasecondfailurewetryagainaftertwoseconds,thenafterfourseconds,andsoon.Atthisrate,ifwehaveadozenfailurestheintervalwillbeoveranhour,inwhichcaseweresetittostartagainatonesecond.Wevarytheretryintervaleachtimetoavoidbeingmistakenforadenialofserviceattackandtoavoidgettingintoan“unlucky”request/failurecycle.AssoonastherequestsucceedsandwehaveresetretryDelaySecbackto1,weparsetheXMLdata.TheQNetworkReplyisaQIODevicesubclass,soinadditiontobeingabletoemitnetworkprogresssignals,itcanalsoemit,forexample,thereadyRead()signal.AndlikeanyotherQIODevicesuchasafile,wecanreaddatafromit,whichbydefaultisreturnedinaQByteArray.TheQDomDocument:setContent()methodcanreadXMLfromaQByteArray,7aQString,orfromaQIODevice,soweareabletodirectlypassittheQNetworkReplyforparsing.IftheQDomDocument:setContent()methodreturnstrue,theparsesucceeded,sowepopulatethetooltipwiththenewdataaprocessthatmightinvolvedownloadinganewicontoo.Iftheparsefailed,weleavetheexistingtooltipasis.Andattheendwesetasingleshottimertorepeattheprocessonehourlater.TheQDomDocumentclassispartofQtsQtXmlmodule,sotobeabletouseitwemustaddthelineQT+=file.Theapplicationsflowofcontrol,fromtheinitialGETrequestontheXMLnetworkaccessmanager,todownloadingtheXMLandicons,andthenrepeatingthedownloadeveryhour,isillustratedbyFigure1.3.Forcompleteness,wewillshowtheprivatepopulateToolTip()method,whichwewillreviewinthreeparts,followedbyitstwoprivatehelpermethods.Hereweextractthetextelementsthatwewanttoincludeinthetooltip,althoughwehaveomittedmostofthecodesinceeachelementfollowsthesame(orverysimilar)patternasthecodeshownforthe“weather”element.TheprivatetextForTag()helpermethodisusedtoretrievethetextforanygiventag.Thisworksbecauseweknowthatfortheweatherdataeverytagisuniqueanddoesnotcontainanynestedtags.8TheiconthatcorrespondstotheprevailingweatherconditionsisidentifiedbytwoXMLelements,the“icon_url_base”andthe“icon_url_name”.WeattempttoextractboththeseelementstextsandtocreateaURLoutofthem.WethentrytoretrievetheiconfromthecacheusingtheURLasthekey.TheQCache:object()methodreturns0ifthereisnoiteminthecachewiththecorrespondingkey.IfweretrievedaQIconpointerfromthecacheweuseitinfactwegetacopy(whichischeapbecauseQtusescopy-on-write,andusefulsinceQCachecandeleteitemsatanytime).Otherwiseweusetheiconnetworkaccessmanagertodownloadtheicon.Andifweinitiatedownloadinganicon,thesignalslotconnectionsetupearlierwillensurethatthereadIcon()slot(coveredshortly)iscalledwhenthedownloadhasfinished.Unfortunately,Qtrichtext(HTML)trayicontooltipsareonlysupportedonX11,soforWindowsandMacOSXsystemsweconverttheHTMLtooltiptexttoplaintext.WedothisbyusingthestaticQTextDocumentFragment:fromHtml()methodtogetaQTextDocumentFragment,andthenusingQTextDocumentFragment:toPlainText(),toproduceplaintext.UsingaQTextDocumentFragmentismoreconvenientthandoingtheconversionbyhandsincenotonlydoesitconvertHTMLentitiestotheappropriateUnicodecharactersandstripoutHTMLtags,butitisalsosmartenoughtoconvertsintonewlines.UsingQDomDocumentisidealforsmallXMLfilessinceitparsestheentirefile,holdsallthedatainmemory,andprovidesavarietyofconvenientaccessmethods.Here,webeginbygettingalistofalltheQDomNodesthatusethespecifiedtag.Ifthelistisnonempty,weretrievethefirstnode.Intheweatherdata,everytagisunique,sothereshouldonlyeverbeonenodeforagiventag.IntheDOMAPI,thetextbetweentagsisheldinachildnode,soitcanberetrievedfromanodebyretrievingthenodesfirstchild,convertingthechildtoatextnode,andthenretrievingitstextdataforexample,node.firstChild().toText().data().Fortunately,QtoffersashortcuttheQDomNode:nodeValue()methodwhichreturnsanodetype-specificstring,whichinthecaseoftextnodesisthetextitself.9Thismethodiscalledwhenarequesttodownloadaniconhasfinished.Webeginbycheckingtoseeifinsteadofthereplyweareexpectingwehavereceivedaredirectofsomekind.IfthisisthecaseweinitiateanewGETrequesttoretrievetheicondatausingtheredirectstargetURL.TheQNetworkAccess-Managerdoesntperformredirectsautomaticallyforsecurityreasons,butherewehavechosentotrustthesite.Ifsecurityisaconcern,weshouldreallychecktheredirectedURLforexample,thatitisfromthesamedomainandthatitdoesntincludesomemaliciousJavaScript.Inthecommoncase,whenthereisnoredirectinforce,wewillgetaninvalidredirectQUrl,andcanproceedtoreadthereplysdata.Ifthereplyisnotaredirecttheneitherwehavetheicondataoranerroroccurred.WereadallthedatathatisavailableintoaQByteArrayandthenfeedthedatatoaQPixmap.IftheQPixmap:loadFromData()methodreturnsfalsetheneithertheicondatawasincomplete,corrupt,orinanunrecognizedformat,ortherewasanetworkerrorandnodatawasretrieved.Inanyofthesecasesweabandontheattempttoretrievetheicon,andthecurrenticonremainsunchanged.Ifthedownloadwassuccessful,weconverttheQPixmapintoaQIconandsettheiconasthetrayicon.ThenweaddtheiconkeyedbyitsURLtotheiconcachesafeintheknowledgethatwewillnevercachemorethan100iconsandthatwewillneverneedlesslydownloadaniconthatisalreadyinthecache.Thisslotiscalledwhenevertheuserchoosesanewairportfromthecontextmenu.Weretrievethenameoftheairport,setthisairportasthenewdefault,andthencallrequestXml()toforcetheapplicationtoretrievefreshweatherdataforthenewlychosenairport.Noticethatwedontsaveanysettingswhentheapplicationterminates;insteadwesavethesettings(inthiscasethereisonlyone)whenevertheyarechanged.Thisapproachhastheadvantagethatthesettingsarealwaysuptodate,evenwhentheapplicationisrunningorinthefaceofanunexpectedcrash,butthedisadvantagethatthecodeforsavingsettingscouldbespreadallovertheplace,makingmaintenancemoreerror-prone.10Wehavenowfinishedreviewingasmallapplicationthatusesthehigh-levelandeasy-to-useQNetworkAccessManagerclasstodobasicInternetdownloading.InadditiontotheWeatherTrayIconapplication,thebooksexamplesalsoincludetheRssPanelapplication(rsspanel)showninFigure1.4.11外文翻译先进的Qt编程“云计算”的无处不在很明显,网络的便捷使得手机和小体积上网本和装备电脑更不用说谷歌文档的文件位置的免部署成本基于web的应用程序,可能导致我们相信桌面应用程序是恐龙,还不知道他们灭绝。但在我们放弃c+和Qt及切换到web编程和JavaScript和HTML的微妙的快乐,值得反思的桌面应用程序可以提供的优势。理想情况下我们希望,享受上网的优点同时,所有桌面应用程序的好处可用。多亏了Qt的QtWebKit模块,介绍了Qt4.4,这可以实现,因为QtWebKit允许我们创建混合桌面/互联网应用程序可以离线和在线工作。相比之下,基于web的应用程序的主要缺点是在开发Qt应用程序必须在用户的电脑上。在这种情况下,部署工作或带宽利用率必须最小化有几种方法可以走。例如,我们可以把大量的应用程序功能独立成相对较小的插件,可以更新。或者我们可以使用应用程序的脚本提供的大部分应用程序的JavaScript使用QtScript模块的功能(ECMAScript)或者第三方模块如果我们想使用一个不同的脚本语言只是在必要时更新或添加单个脚本。或者我们可以把尽可能多的功能到服务器到web页面的脚本,从而大大减少的次数,我们需要更新客户端。在这一章里,我们将专注于Qt支持混合应用程序的关键方面。在第一部分中,我们将使用方便QNetworkAccessManager类,创建Internet-aware小部件。在第二部分,我们将利用QtWebKit模块,开始通过开发一个通用的web浏览器组件一个令人惊讶的简单的任务由于QtWebKit模块所提供的功能。我们将利用通用的web浏览器component-for示例中,创建一个web站点应用程序-并且使用QtWebKit模块访问DOM(文档对象模型)的幕后网页下载,这样我们才能从他们中提取信息进一步处理。然后我们将看到如何嵌入Qtwidgets-including自己定制widgets-into网页,提供功能不可用使用标准的HTML小部件。作为一次性的事件时,我们把Internet-aware小部件看作一个小部件的定义,自动或定期从互联网上获取数据。最简单的方法是创建一个小部件创建一个Internet-aware小部件利用QNetworkAccessManager对象的子类。这些对象可以执行HTTP(HTTPS)头,POST、GET、PUT请求,还处理cookie(使用QNetworkCookieJar)和身份验证(使用QAuthenticator)。在本节中,我们将看一个例

温馨提示

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

评论

0/150

提交评论