QGIS-2.8-PyQGISDeveloperCookbook-en

更新时间:2023-05-17 05:42:01 阅读量: 实用文档 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

PyQGISdevelopercookbook

Release2.8

QGISProject

August24,2015

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

Contents

1Introduction

1.1RunPythoncodewhenQGISstarts

1.2PythonConsole...........

1.3PythonPlugins...........

1.4PythonApplications............................................................................................................................................11223

5

7

7

8

9

11

11

11

13

13

15

15

15

15

17

18

19

20

21

22

29

31

31

31

32

33

33

34

35

35

362LoadingProjects3LoadingLayers3.1VectorLayers.............................................3.2RasterLayers.............................................3.3MapLayerRegistry.....................................................................................................................................................................................................................................................................................................................................................................................................................................................................................4UsingRasterLayers4.1LayerDetails...4.2DrawingStyle..4.3RefreshingLayers4.4QueryValues...5UsingVectorLayers5.1Retrievinginformationsaboutattributes.....5.2Selectingfeatures.................5.3IteratingoverVectorLayer............5.4ModifyingVectorLayers.............5.5ModifyingVectorLayerswithanEditingBuffer5.6UsingSpatialIndex...............5.7WritingVectorLayers..............5.8MemoryProvider.................5.9Appearance(Symbology)ofVectorLayers...5.10FurtherTopics..................6GeometryHandling6.1GeometryConstruction.......................................6.2AccesstoGeometry.........................................6.3GeometryPredicatesandOperations................................7ProjectionsSupport7.1Coordinatereferencesystems....................................7.2Projections..............................................8UsingMapCanvas8.1EmbeddingMapCanvas.......................................8.2UsingMapToolswithCanvas....................................

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

8.3

8.4

8.5

9RubberBandsandVertexMarkers..................................WritingCustomMapTools.....................................WritingCustomMapCanvasItems.................................37383941

41

42

42

45

46

46

46

49

51

51

52

53

55

55

56

60

61

61

62

66

67

67

69

69

71

71

71

71

75

75

75

75

77

77

77

79

85MapRenderingandPrinting9.1SimpleRendering..........................................9.2RenderinglayerswithdifferentCRS.................................9.3OutputusingMapComposer.....................................10Expressions,FilteringandCalculatingValues10.1ParsingExpressions.........................................10.2EvaluatingExpressions........................................10.3Examples...............................................11ReadingAndStoringSettings12Communicatingwiththeuser12.1Showingmessages.TheQgsMessageBarclass.........................12.2Showingprogress..........................................12.3Logging................................................13DevelopingPythonPlugins13.1Writingaplugin...........................................13.2Plugincontent............................................13.3Documentation............................................14IDEsettingsforwritinganddebuggingplugins14.1Anoteoncon guringyourIDEonWindows............................14.2DebuggingusingEclipseandPyDev................................14.3DebuggingusingPDB........................................15UsingPluginLayers15.1SubclassingQgsPluginLayer.....................................16CompatibilitywitholderQGISversions16.1Pluginmenu.............................................17Releasingyourplugin17.1Metadataandnames.........................................17.2Codeandhelp............................................17.3Of cialpythonpluginrepository..................................18CodeSnippets18.1Howtocallamethodbyakeyshortcut...............................18.2HowtotoggleLayers........................................18.3Howtoaccessattributetableofselectedfeatures..........................19Networkanalysislibrary19.1Generalinformation.........................................19.2Buildingagraph...........................................19.3Graphanalysis............................................Index

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

CHAPTER1Introduction

Thisdocumentisintendedtoworkbothasatutorialandareferenceguide.Whileitdoesnotlistallpossibleuse

cases,itshouldgiveagoodoverviewoftheprincipalfunctionality.

Startingfrom0.9release,QGIShasoptionalscriptingsupportusingPythonlanguage.We’vedecidedforPython

asit’soneofthemostfavouritelanguagesforscripting.PyQGISbindingsdependonSIPandPyQt4.Thereason

forusingSIPinsteadofmorewidelyusedSWIGisthatthewholeQGIScodedependsonQtlibraries.Python

bindingsforQt(PyQt)aredonealsousingSIPandthisallowsseamlessintegrationofPyQGISwithPyQt.

TODO:GettingPyQGIStowork(Manualcompilation,Troubleshooting)

ThereareseveralwayshowtouseQGISpythonbindings,theyarecoveredindetailinthefollowingsections:

automaticallyrunPythoncodewhenQGISstarts

issuecommandsinPythonconsolewithinQGIS

createandusepluginsinPython

createcustomapplicationsbasedonQGISAPI

ThereisacompleteQGISAPIreferencethatdocumentstheclassesfromtheQGISlibraries.PythonicQGISAPI

isnearlyidenticaltotheAPIinC++.

TherearesomeresourcesaboutprogrammingwithPyQGISonQGISblog.SeeQGIStutorialportedtoPythonfor

someexamplesofsimple3rdpartyapps.Agoodresourcewhendealingwithpluginsistodownloadsomeplugins

frompluginrepositoryandexaminetheircode.Also,thepython/plugins/folderinyourQGISinstallation

containssomepluginthatyoucanusetolearnhowtodevelopsuchpluginandhowtoperformsomeofthemost

commontasks

1.1RunPythoncodewhenQGISstarts

TherearetwodistinctmethodstorunPythoncodeeverytimeQGISstarts.

1.1.1PYQGIS_STARTUPenvironmentvariable

YoucanrunPythoncodejustbeforeQGISinitializationcompletesbysettingthePYQGIS_STARTUPenviron-

mentvariabletothepathofanexistingPython le.

Thismethodissomethingyouwillprobablyrarelyneed,butworthmentioningherebecauseitisoneoftheseveral

waystorunPythoncodewithinQGISandbecausethiscodewillrunbeforeQGISinitializationiscomplete.This

methodisveryusefulforcleaningsys.path,whichmayhaveundesireablepaths,orforisolating/loadingtheinitial

environwithoutrequiringavirtenv,e.g.homebreworMacPortsinstallsonMac.

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

1.1.2Thestartup.py le

EverytimeQGISstarts,theuser’sPythonhomedirectory(usually:.qgis2/python)issearchedfora le

namedstartup.py,ifthat leexists,itisexecutedbytheembeddedPythoninterpreter.

1.2PythonConsole

Forscripting,itispossibletotakeadvantageofintegratedPythonconsole.Itcanbeopenedfrommenu:Plugins

→PythonConsole.Theconsoleopensasanon-modalutility

window:

Figure1.1:QGISPythonconsole

Thescreenshotaboveillustrateshowtogetthelayercurrentlyselectedinthelayerlist,showitsIDandoptionally,

ifitisavectorlayer,showthefeaturecount.ForinteractionwithQGISenvironment,thereisaifacevariable,

whichisaninstanceofQgsInterface.Thisinterfaceallowsaccesstothemapcanvas,menus,toolbarsand

otherpartsoftheQGISapplication.

Forconvenienceoftheuser,thefollowingstatementsareexecutedwhentheconsoleisstarted(infutureitwillbe

possibletosetfurtherinitialcommands)

Forthosewhichusetheconsoleoften,itmaybeusefultosetashortcutfortriggeringtheconsole(withinmenu

Settings→Con gureshortcuts...)

1.3PythonPlugins

QGISallowsenhancementofitsfunctionalityusingplugins.ThiswasoriginallypossibleonlywithC++language.

WiththeadditionofPythonsupporttoQGIS,itisalsopossibletousepluginswritteninPython.Themain

advantageoverC++pluginsisitssimplicityofdistribution(nocompilingforeachplatformneeded)andeasier

development.

ManypluginscoveringvariousfunctionalityhavebeenwrittensincetheintroductionofPythonsupport.Theplu-

gininstallerallowsuserstoeasilyfetch,upgradeandremovePythonplugins.SeethePythonPluginRepositories

pageforvarioussourcesofplugins.

CreatingpluginsinPythonissimple,seeDevelopingPythonPluginsfordetailedinstructions.

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

1.4PythonApplications

OftenwhenprocessingsomeGISdata,itishandytocreatesomescriptsforautomatingtheprocessinsteadof

doingthesametaskagainandagain.WithPyQGIS,thisisperfectlypossible—importtheqgis.coremodule,

initializeitandyouarereadyfortheprocessing.

OryoumaywanttocreateaninteractiveapplicationthatusessomeGISfunctionality—measuresomedata,

exportamapinPDForanyotherfunctionality.Theqgis.guimoduleadditionallybringsvariousGUIcompo-

nents,mostnotablythemapcanvaswidgetthatcanbeveryeasilyincorporatedintotheapplicationwithsupport

forzooming,panningand/oranyfurthercustommaptools.

1.4.1UsingPyQGISincustomapplication

Note:donotuseqgis.pyasanameforyourtestscript—Pythonwillnotbeabletoimportthebindingsasthe

script’snamewillshadowthem.

Firstofallyouhavetoimportqgismodule,setQGISpathwheretosearchforresources—databaseofprojections,

providersetc.Whenyousetpre xpathwithsecondargumentsetasTrue,QGISwillinitializeallpathswith

standarddirunderthepre xdirectory.CallinginitQgis()functionisimportanttoletQGISsearchforthe

availableproviders.

NowyoucanworkwithQGISAPI—loadlayersanddosomeprocessingor reupaGUIwithamapcanvas.

Thepossibilitiesareendless:-)

Whenyouaredonewithusing

QGISlibrary,callexitQgis()tomakesurethateverythingiscleanedup(e.g.

clearmaplayerregistryanddeletelayers):

1.4.2RunningCustomApplications

YouwillneedtotellyoursystemwheretosearchforQGISlibrariesandappropriate

Pythonmodulesiftheyare

notinawell-knownlocation—otherwisePythonwillcomplain:

Thiscanbe xedbysettingthePYTHONPATHenvironmentvariable.Inthefollowingcommands,qgispath

shouldbereplacedwithyouractualQGISinstallationpath:

onLinux:exportPYTHONPATH=/qgispath/share/qgis/python

onWindows:setPYTHONPATH=c:\qgispath\python

ThepathtothePyQGISmodulesisnowknown,howevertheydependonqgis_coreandqgis_guilibraries

(thePythonmodulesserveonlyaswrappers).Pathtotheselibrariesistypicallyunknownfortheoperatingsystem,

soyougetanimporterroragain

(themessagemightvarydependingonthesystem):

FixthisbyaddingthedirectorieswheretheQGISlibrariesresidetosearchpathofthedynamiclinker:

onLinux:exportLD_LIBRARY_PATH=/qgispath/lib

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

onWindows:setPATH=C:\qgispath;%PATH%

Thesecommandscanbeputintoabootstrapscriptthatwilltakecareofthestartup.Whendeployingcustom

applicationsusingPyQGIS,thereareusuallytwopossibilities:

requireusertoinstallQGISonhisplatformpriortoinstallingyourapplication.Theapplicationinstaller

shouldlookfordefaultlocationsofQGISlibrariesandallowusertosetthepathifnotfound.Thisapproach

hastheadvantageofbeingsimpler,howeveritrequiresusertodomoresteps.

packageQGIStogetherwithyourapplication.Releasingtheapplicationmaybemorechallengingandthe

packagewillbelarger,buttheuserwillbesavedfromtheburdenofdownloadingandinstallingadditional

piecesofsoftware.

Thetwodeploymentmodelscanbemixed-deploystandaloneapplicationonWindowsandMacOSX,forLinux

leavetheinstallationofQGISuptouserandhispackagemanager.

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

CHAPTER2

LoadingProjects

Sometimesyouneedtoloadanexistingprojectfromapluginor(moreoften)whendevelopingastand-alone

QGISPythonapplication(see:PythonApplications).

ToloadaprojectintothecurrentQGISaplicationyouneedaQgsProjectinstance()objectandcallits

read()methodpassingtoitaQFileInfoobjectthatcontainsthepathfromwheretheprojectwillbeloaded:

Incaseyouneedtomakesomemodi cationstotheproject(forexampleaddorremovesomelayers)andsave

yourchanges,youcancallthewrite()methodofyourprojectinstance.Thewrite()methodalsoacceptsan

optionalQFileInfothatallowsyoutospecifyapathwheretheprojectwillbesaved:

Bothread()andwrite()funtionsreturnabooleanvaluethatyoucanusetocheckiftheoperationwas

successful.

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

PyQGISdevelopercookbook,Release2.8

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

CHAPTER3

LoadingLayers

Let’sopensomelayerswithdata.QGISrecognizesvectorandrasterlayers.Additionally,customlayertypesare

available,butwearenotgoingtodiscussthemhere.

3.1VectorLayers

Toloadavectorlayer,specifylayer’sdatasourceidenti er,nameforthelayerandprovider’sname:

Thedatasourceidenti erisastringanditisspeci yer’snameisusedinthe

layerlistwidget.Itisimportanttocheckwhetherthelayerhasbeenloadedsuccessfully.Ifitwasnot,aninvalid

layerinstanceisreturned.

ThequickestwaytoopenanddisplayavectorlayerinQGISistheaddVectorLayerfunctionofthe

QgisInterface:

,"ogr")Thiscreatesanewlayerandaddsittothemaplayerregistry(makingitappearinthelayerlist)inonestep.The

functionreturnsthelayerinstanceorNoneifthelayercouldn’tbeloaded.

Thefollowinglistshowshowtoaccessvariousdatasourcesusingvectordataproviders:

OGRlibrary(shape lesandmanyother leformats)—data

sourceisthepathtothe le

)

PostGISdatabase—datasourceisastringwithallinformationneededtocreateaconnectiontoPostgreSQL

database.QgsDataSourceURIclasscangeneratethisstringforyou.NotethatQGIShastobecompiled

withPostgressupport,otherwisethisproviderisn’tavailable.

CSVorotherdelimitedtext les—toopena lewithasemicolonasadelimiter,with eld“x”forx-

coordinateand eld“y”withy-coordinateyouwouldusesomethinglikethis

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

Note:fromQGISversion1.7theproviderstringisstructuredasaURL,sothepathmustbepre xedwith

le://.AlsoitallowsWKT(wellknowntext)formattedgeometriesasanalternativeto“x”and“y” elds,

andallowsthe

coordinatereferencesystemtobespeci ed.Forexample

"shape") GPX les—the“gpx”dataproviderreadstracks,routesandwaypointsfromgpx les.Toopena le,the

type(track/route/waypoint)needstobespeci edaspartoftheurl

SpatiaLitedatabase—supportedfromQGISv1.1.SimilarlytoPostGISdatabases,QgsDataSourceURI

canbeusedforgenerationofdatasourceidenti er

MySQLWKB-basedgeometries,throughOGR—datasourceistheconnectionstringtothetable

WFSconnection:.theconnectionisde nedwithaURIandusingtheWFSprovider

Theuricanbecreatedusingthestandardurllib

library.

3.2RasterLayers

Foraccessingraster les,GDALlibraryisused.Itsupportsawiderangeof leformats.Incaseyouhavetroubles

withopeningsome les,checkwhetheryourGDALhassupportfortheparticularformat(notallformatsare

availablebydefault).Toloadarasterfroma le,specifyits

lenameandbasename

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

Similarlytovectorlayers,rasterlayerscanbeloadedusingtheaddRasterLayerfunctionoftheQgisInterface:

Thiscreatesanewlayerandaddsittothemaplayerregistry(makingitappearinthelayerlist)inonestep.

RasterlayerscanalsobecreatedfromaWCSservice.

detailedURIsettingscanbefoundinproviderdocumentation

AlternativelyyoucanloadarasterlayerfromWMSserver.Howevercurrentlyit’snotpossibletoaccessGetCa-

pabilitiesresponsefromAPI—youhaveto

knowwhatlayersyouwant

3.3MapLayerRegistry

Ifyouwouldliketousetheopenedlayersforrendering,donotforgettoaddthemtomaplayerregistry.Themap

layerregistrytakesownershipoflayersandtheycanbelateraccessedfromanypartoftheapplicationby

their

uniqueID.Whenthelayerisremovedfrommaplayerregistry,itgetsdeleted,too.

Addingalayertotheregistry

Layersaredestroyedautomaticallyonexit,howeverifyouwanttodeletethelayer

explicitly,use

Foralistofloadedlayersandlayerids,use

TODO:Moreaboutmaplayerregistry?

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

PyQGIS developer cookbook, Release 2.8

10

Chapter 3. Loading Layers

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

CHAPTER4

UsingRasterLayers

Thissectionslistsvariousoperationsyoucandowithrasterlayers.

4.1LayerDetails

Arasterlayerconsistsofoneormorerasterbands—itisreferredtoaseithersinglebandormultibandraster.

ualcolorimage(e.g.aerialphoto)isarasterconsistingofred,blueand

greenband.Singlebandlayerstypicallyrepresenteithercontinuousvariables(e.g.elevation)ordiscretevariables

(nduse).Insomecases,arasterlayercomeswithapaletteandrastervaluesrefertocolorsstoredinthe

palette:

4.2DrawingStyle

Whenarasterlayerisloaded,itgetsadefaultdrawingstylebasedonitstype.Itcanbealteredeitherinraster

layerpropertiesorprogrammatically.Thefollowingdrawingstylesexist:

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

dex

2

3

4

5

7

8

9QgsRasterLater.XSingleBandPseudoColorPalettedColorPalettedSingleBandGrayPalettedSingleBandPseudo-ColorMultiBandSingleBandGrayMultiBandSingle-BandPseudoColorMultiBandColor

Singlebandimagedrawnusingapseudocoloralgorithm“Palette”imagedrawnusingcolortable“Palette”layerdrawningrayscale“Palette”layerdrawnusingapseudocoloralgorithmLayercontaining2ormorebands,butasinglebanddrawnasarangeofgraycolorsLayercontaining2ormorebands,butasinglebanddrawnusingapseudocoloralgorithmLayercontaining2ormorebands,mappedtoRGBcolorspace.

Toquerythecurrentdrawingstyle:

Singlebandrasterlayerscanbedrawneitheringraycolors(lowvalues=black,highvalues=white)orwitha

pseudocoloralgorithmthatassignscolorsforvaluesfromthesingleband.Singlebandrasterswithapalettecan

beadditionallydrawnusingtheirpalette.MultibandlayersaretypicallydrawnbymappingthebandstoRGB

colors.Otherpossibilityistousejustonebandforgrayorpseudocolordrawing.

Thefollowingsectionsexplainhowtoqueryandmodifythelayerdrawingstyle.Afterdoingthechanges,you

mightwanttoforceupdateofmapcanvas,seeRefreshingLayers.

TODO:contrastenhancements,transparency(nodata),userde nedmin/max,bandstatistics

4.2.1SingleBandRasters

Theyarerenderedingraycolorsbydefault.Tochangethedrawingstyletopseudocolor:

ThePseudoColorShaderisabasicshaderthathighlightslowvaluesinblueandhighvaluesinred.Thereis

alsoColorRampShaderwhichmapsthecolorsasspeci edbyitscolormap.Ithasthreemodesof

interpolationofvalues:

linear(INTERPOLATED):resultingcolorislinearlyinterpolatedfromthecolormapentriesaboveand

belowtheactualpixelvalue

discrete(DISCRETE):colorisusedfromthecolormapentrywithequalorhighervalue

exact(EXACT):colorisnotinterpolated,onlythepixelswithvalueequaltocolormapentriesaredrawn

Tosetaninterpolatedcolorrampshaderrangingfromgreentoyellowcolor(forpixelvaluesfrom0to255):

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

Toreturnbacktodefaultgraylevels,use:

4.2.2MultiBandRasters

Bydefault,QGISmapsthe rstthreebandstored,greenandbluevaluestocreateacolorimage(thisisthe

MultiBandColordrawingstyle.Insomecasesyoumightwanttooverridethesesetting.Thefollowingcode

interchangesredband(1)andgreenband(2):

4.3RefreshingLayers

Ifyoudochangelayersymbologyandwouldlikeensurethatthechangesareimmediatelyvisibletotheuser,call

these

methods

The rstcallwillensurethatthecachedimageofrenderedlayeriserasedincaserendercachingisturnedon.

ThisfunctionalityisavailablefromQGIS1.4,inpreviousversionsthisfunctiondoesnotexist—tomakesure

thatthecodeworkswithallversionsofQGIS,we rstcheckwhetherthemethodexists.

Thesecondcallemitssignalthatwillforceanymapcanvascontainingthelayertoissuearefresh.

WithWMSrasterlayers,thesecommandsdonotwork.Inthiscase,

youhavetodoitexplicitly

Incaseyouhavechangedlayersymbology(seesectionsaboutrasterandvectorlayersonhowtodothat),you

mightwanttoforceQGIStoupdatethelayersymbologyinthelayerlist(legend)widget.Thiscanbedoneas

follows(ifaceisaninstanceofQgisInterface)

4.4QueryValues

Todoaqueryonvalueofbandsofrasterlayeratsomespeci edpoint

Theresultsmethodinthiscasereturnsa

dictionary,withbandindicesaskeys,andbandvaluesasvalues.

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

PyQ

GIS developer cookbook, Release 2.8

14

Chapter 4. Using Raster Layers

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

CHAPTER5

UsingVectorLayers

Thissectionsummarizesvariousactionsthatcanbedonewithvectorlayers.

5.1Retrievinginformationsaboutattributes

Youcanretrieveinformationsaboutthe eldsassociatedwithavectorlayerbycallingpendingFields()on

aQgsVectorLayerinstance:

5.2Selectingfeatures

InQGISdesktop,featurescanbeselectedindifferentways,theusercanclickonafeature,drawarectangleon

themapcanvasoruseanexpression lter.Selectedfaturesarenormallyhiglightedinadifferentcolor(defaultis

yellow)todrawuser’sattentionontheselection.Sometimescanbeusefultoprogrammaticallyselectfeaturesor

tochangethedefaultcolor.

TochangetheselectioncoloryoucanusesetSelectionColor()methodof

QgsMapCanvasasshownin

thefollowingexample:

Toaddaddfeaturestotheselectedfeatureslistforagivenlayer,youcancallsetSelectedFeatures()

passingtoitthelistoffeaturesIDs:

Tocleartheselection,justpassanemptylist:

5.3IteratingoverVectorLayer

Iteratingoverthefeaturesinavectorlayerisoneofthemostcommontasks.Belowisanexampleofthesimple

basiccodetoperformthistaskandshowingsomeinformationabouteachfeature.thelayervariableisassumed

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

tohaveaQgsVectorLayerobject

5.3.1Accessingattributes

Attributescanbereferredtobytheir

name.

Alternatively,attributescanbereferredtobyindex.Thisiswillbeabitfasterthanusingthename.Forexample,

togetthe rstattribute:

5.3.2Iteratingoverselectedfeatures

ifyouonlyneedselectedfeatures,youcanusetheselectedFeatures()methodfromvectorlayer:

AnotheroptionistheProcessingfeatures()method:

Bydefault,thiswilliterateoverallthefeaturesinthelayer,incasethereisnoselection,orovertheselected

featuresotherwise.NotethatthisbehaviorcanbechangedintheProcessingoptionstoignoreselections.

为开发人员准备的文档,涵盖QGIS的多种功能实现和代码。

5.3.3Iteratingoverasubsetoffeatures

Ifyouwanttoiterateoveragivensubsetoffeaturesinalayer,suchasthosewithinagivenarea,youhavetoadd

aQgsFeatureRequestobjecttothegetFeatures()call.Here’sanexample

Ifyouneedanattribute-based lterinstead(orinaddition)ofaspatialonelikeshownintheexampleabove,you

canbuildanQgsExpressionobjectandpassittotheQgsFeatureRequestconstructor.Here’sanexample

Therequestcanbeusedtode nethedataretrievedforeachfeature,sotheiteratorreturnsallfeatures,butreturns

partialdataforeachofthem.

Tip:Ifyouonlyneedasubsetoftheattributesoryoudon’tneedthegeometryinformations,youcansigni cantlyincreasethespeedofthefeaturesrequestbyusingQgsFeatureRequest.NoGeometry agorspecifyinga

subsetofattributes(possiblyempty)likeshownintheexampleabove.

5.4ModifyingVectorLayers

Mostvectordataproviderssupportediting

oflayerdata.Sometimestheysupportjustasubsetofpossibleediting

ethecapabilities()functionto ndoutwhatsetoffunctionalityissupported

Byusinganyofthefollowingmethodsforvectorlayerediting,thechangesaredirectlycommittedtotheunderly-

ingdatastore(a le,databaseetc).Incaseyouwouldliketodoonlytemporarychanges,skiptothenextsection

thatexplainshowtodomodi cationswitheditingbuffer.

Note:IfyouareworkinginsideQGIS(eitherfromtheconsoleorfromaplugin),itmightbenecessarytoforcearedrawofthemapcanvasinordertoseethechangesyou’vedonetothegeometry,tothestyleortotheattributes:

5.4.1AddFeatures

CreatesomeQgsFeatureinstancesandpassalistofthemtoprovider’saddFeatures()method.Itwill

returntwovalues:result(true/false)andlistofaddedfeatures(theirIDissetbythedatastore)

本文来源:https://www.bwwdw.com/article/kfz4.html

Top