Qt WebKit中英文翻译.docx
《Qt WebKit中英文翻译.docx》由会员分享,可在线阅读,更多相关《Qt WebKit中英文翻译.docx(22页珍藏版)》请在冰豆网上搜索。
QtWebKit中英文翻译
原文:
QtWebKit
1.QWebElement
TheQWebElementclassprovidesconvenientaccesstoDOMelementsinaQWebFrame.
AQWebElementobjectallowseasyaccesstothedocumentmodel,representedbyatree-likestructureofDOMelements.TherootofthetreeiscalledthedocumentelementandcanbeaccessedusingQWebFrame:
:
documentElement().
SpecificelementscanbeaccessedusingfindAll()andfindFirst().TheseelementsareidentifiedusingCSSselectors.ThecodesnippetbelowdemonstratestheuseoffindAll().
QWebElementdocument=frame->documentElement();
/*Assumethedocumenthasthefollowingstructure:
Intro
Snippets
Content
Here
*/
QWebElementCollectionallSpans=document.findAll("span");
QWebElementCollectionintroSpans=document.findAll("p.introspan");
Thefirstlistcontainsallspanelementsinthedocument.Thesecondlistcontainsspanelementsthatarechildrenofp,classifiedwithintro.
UsingfindFirst()ismoreefficientthancallingfindAll(),andextractingthefirstelementonlyinthelistreturned.
AlternativelyyoucantraversethedocumentmanuallyusingfirstChild()andnextSibling():
frame->setHtml("
FirstParagraph
SecondParagraph
");
QWebElementdoc=frame->documentElement();
QWebElementbody=doc.firstChild();
QWebElementfirstParagraph=body.firstChild();
QWebElementsecondParagraph=firstParagraph.nextSibling();
Individualelementscanbeinspectedorchangedusingmethodssuchasattribute()orsetAttribute().Forexamle,tocapturetheuser'sinputinatextfieldforlateruse(auto-completion),abrowsercoulddosomethinglikethis:
QWebElementfirstTextInput=document.findFirst("input[type=text]");
QStringstoredText=firstTextInput.attribute("value");
Whenthesamepageislaterrevisited,thebrowsercanfillinthetextfieldautomaticallybymodifyingthevalueattributeoftheinputelement:
QWebElementfirstTextInput=document.findFirst("input[type=text]");
textInput.setAttribute("value",storedText);
Anotherusecaseistoemulateaclickeventonanelement.ThefollowingcodesnippetdemonstrateshowtocalltheJavaScriptDOMmethodclick()ofasubmitbutton:
QWebElementdocument=frame->documentElement();
/*Assumethatthedocumenthasthefollowingstructure:
*/
QWebElementbutton=document.findFirst("input[type=submit]");
button.evaluateJavaScript("click()");
TheunderlyingcontentofQWebElementisexplicitlyshared.CreatingacopyofaQWebElementdoesnotcreateacopyofthecontent.Instead,bothinstancespointtothesameelement.
ThecontentsofchildelementscanbeconvertedtoplaintextwithtoPlainText();toXHTMLusingtoInnerXml().Toincludetheelement'stagintheoutput,usetoOuterXml().
ItispossibletoreplacethecontentsofchildelementsusingsetPlainText()andsetInnerXml().Toreplacetheelementitselfanditscontents,usesetOuterXml().
2.QtWebKit
Overview
Thetechnology
TheQtWebKitbridgeisamechanismthatextendsWebKit'sJavaScriptenvironmenttoaccessnativeobjectsthatarerepresentedasQObjects.IttakesadvantageoftheQObjectintrospection,apartoftheObjectModel,whichmakesiteasytointegratewiththedynamicJavaScriptenvironment,forexampleQObjectpropertiesmapdirectlytoJavaScriptproperties.
Forexample,bothJavaScriptandQObjectshaveproperties:
aconstructthatrepresentagetter/setterpairunderonename.
UseCases
TherearetwomainusecasesfortheQtWebKitbridge.Webcontentinanativeapplication,andThinClients.
WebContentinaNativeApplication
ThisisacommonusecaseinclassicQtapplication,andadesignpatternusedbyseveralmodernapplications.Forexample,anapplicationthatcontainsamedia-player,playlistmanager,andmusicstore.Theplaylistmanagerisusuallybestauthoredasaclassicdesktopapplication,withthenative-lookingrobustQWidgetshelpingwithproducingthatapplication.Themedia-playercontrol,whichusuallylookscustom,canbewrittenusingtheGraphicsViewframeworkorwithinadeclarativewaywithQtDeclarative.Themusicstore,whichshowsdynamiccontentfromtheinternetandgetsmodifiedrapidly,isbestauthoredinHTMLandmaintainedontheserver.
WiththeQtWebKitbridge,thatmusicstorecomponentcaninteractwithnativepartsoftheapplication,forexample,ifafileneedstobesavedtoaspecificlocation.
ThinClient
AnotherusecaseisusingQtasanativebackendtoafullwebapplication,referredtohereasathinclient.Inthisuse-case,theentireUIisdrivenbyHTML,JavaScriptandCSS,andnativeQt-basedcomponentsareusedtoallowthatapplicationaccesstonativefeaturesnotusuallyexposedtotheweb,ortoenablehelpercomponentsthatarebestwrittenwithC++.
AnexampleforsuchaclientisaUIforavideo-on-demandserviceonaTV.TheentirecontentandUIcanbekeptontheserver,serveddynamicallythroughHTTPandrenderedwithWebKit,withadditionalnativecomponentsforaccessinghardware-specificfeatureslikeextractingthelistofimagesoutofthevideo.
DifferencefromOtherBridgeTechnologies
OfcourseQtWebKitisnottheonlybridgetechnologyoutthere.NPAPI,forexample,isalong-timestandardorweb-nativebridging.DuetoQt'smeta-objectsystem,fullapplicationsbuiltpartiallywithweb-technologiesaremucheasiertodevelop.NPAPI,however,ismoregearedtowardscross-browserplugins,duetoitbeinganacceptedstandard.
Whendevelopingapluginforabrowser,NPAPIisrecommended.WhendevelopingafullapplicationthatutilizesHTML-rendering,theQtWebKitbridgeisrecommended.
AccessingQObjects
CreatingthelinkviaQWebFrame
Bydefault,noQObjectsareaccessiblethroughthewebenvironment,forsecurityreasons.ToenablewebcontentaccessforanativeQObject,theapplicationmustexplicitlygrantitaccess,usingthefollowingcall:
//...
QWebFrame*frame=myWebPage->mainFrame();
frame->addToJavaScriptWindowObject("someNameForMyObject",myObject);
//...
SeeQWebFrame:
:
addToJavaScriptWindowObject()formoreinformation.
UsingSignalsandSlots
TheQtWebKitbridgeadaptsQt'scentralSignalsandSlotsfeatureforscripting.TherearethreeprincipalwaystousesignalsandslotswiththeQtWebKitbridge:
HybridC++/script:
C++applicationcodeconnectsasignaltoascriptfunction.Forexample,thescriptfunctioncanbeafunctionthattheuserhastypedin,oronethatyouhavereadfromafile.ThisapproachisusefulifyouhaveaQObjectbutdon'twanttoexposetheobjectitselftothescriptingenvironment;youjustwantascripttobeabletodefinehowasignalshouldbereactedto,andleaveituptotheC++sideofyourapplicationtoestablishtheconnection.
Hybridscript/C++:
Ascriptcanconnectsignalsandslotstoestablishconnectionsbetweenpre-definedobjectsthattheapplicationexposestothescriptingenvironment.Inthisscenario,theslotsthemselvesarestillwritteninC++,butthedefinitionoftheconnectionsisfullydynamic(script-defined).
Purelyscript-defined:
Ascriptcanbothdefinesignalhandlerfunctions(effectively"slotswritteninJavaScript"),andsetuptheconnectionsthatutilizethosehandlers.Forexample,ascriptcandefineafunctionthatwillhandletheQLineEdit:
:
returnPressed()signal,andthenconnectthatsignaltothescriptfunction.
NotethatQtScriptfunctionssuchasqScriptConnectareunavilableinthewebenvironment.
SignaltoFunctionConnections
connect(function);
Inthisformofconnection,theargumenttoconnect()isthefunctiontoconnecttothesignal.
functionmyInterestingScriptFunction(){...}
...
myQObject.somethingChanged.connect(myInterestingScriptFunction);
TheargumentcanbeaJavaScriptfunction,asintheaboveexample,oritcanbeaQObjectslot,asinthefollowingexample:
myQObject.somethingChanged.connect(myOtherQObject.doSomething);
WhentheargumentisaQObjectslot,theargumenttypesofthesignalandslotdonotnecessarilyhavetobecompatible;Ifnecessary,theQtWebKitbridgewill,performconversionofthesignalargumentstomatchtheargumenttypesoftheslot.
Todisconnectfromasignal,youinvokethesignal'sdisconnect()function,passingthefunctiontodisconnectasargument:
myQObject.somethingChanged.disconnect(myInterestingFunction);
myQObject.somethingChanged.disconnect(myOtherQObject.doSomething);
Whenascriptfunctionisinvokedinresponsetoasignal,thethisobjectwillbetheGlobalObject.
SignaltoMemberFunctionConnections
connect(thisObject,function)
Inthisformoftheconnect()function,thefirstargumentistheobjectthatwillbeboundtothevariable,this,whenthefunctionspecifiedusingthesecondargumentisinvoked.
Ifyouhaveapushbuttoninaform,youtypicallywanttodosomethinginvolvingtheforminresponsetothebutton'sclickedsignal;passingtheformasthethisobjectmakessenseinsuchacase.
varobj={x:
123};
varfun=function(){print(this.x);};
myQObject.somethingChanged.connect(obj,fun);
Todisconnectfromthesignal,passthesameargumentstodisconnect():
myQObject.somethingChanged.disconnect(obj,fun);
SignaltoNamedMemberFunctionConnections
connect(thisObject,functionName)
Thisformoftheconnect()functionrequiresthatthefirstargumentistheobjectthatwillbeboundtothevariablethiswhenafunctionisinvokedinresponsetothesignal.Thesecondargumentspecifiesthenameofafunctionthatisconnectedtothesignal,andthisreferstoamemberfunctionoftheobject