Python Scripting in QGIS to add features and select them? Planned maintenance scheduled April 23, 2019 at 23:30UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?PyQGIS, features geometry type changes to unknown after copying to another layerqgis processing not add layerDeleting all Features of a Vector Layer in pyQGISSelect features and zoom to selection on standalone QGis applicationHow to get the BBOX of selected features in QGIS using the UI?Run QGIS layer Action on all selected featuresFeature Selection Using Custom Python Expression Functions in QGIS 2.18No “committedFeaturesAdded” signal after dataProvider().addFeatures() - QGiS 2.14.8Run QGIS Model on selected features only?Using file path in QgsVectorLayer?

C's equality operator on converted pointers

How to report t statistic from R

Semigroups with no morphisms between them

Would it be easier to apply for a UK visa if there is a host family to sponsor for you in going there?

How often does castling occur in grandmaster games?

An adverb for when you're not exaggerating

Why does it sometimes sound good to play a grace note as a lead in to a note in a melody?

Why are my pictures showing a dark band on one edge?

Does the Mueller report show a conspiracy between Russia and the Trump Campaign?

Antipodal Land Area Calculation

Intuitive explanation of the rank-nullity theorem

Lagrange four-squares theorem --- deterministic complexity

How many morphisms from 1 to 1+1 can there be?

What initially awakened the Balrog?

How does the math work when buying airline miles?

A term for a woman complaining about things/begging in a cute/childish way

Karn the great creator - 'card from outside the game' in sealed

Crossing US/Canada Border for less than 24 hours

Flash light on something

What does this say in Elvish?

How can I prevent/balance waiting and turtling as a response to cooldown mechanics

What would you call this weird metallic apparatus that allows you to lift people?

Drawing spherical mirrors

Why are vacuum tubes still used in amateur radios?



Python Scripting in QGIS to add features and select them?



Planned maintenance scheduled April 23, 2019 at 23:30UTC (7:30pm US/Eastern)
Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?PyQGIS, features geometry type changes to unknown after copying to another layerqgis processing not add layerDeleting all Features of a Vector Layer in pyQGISSelect features and zoom to selection on standalone QGis applicationHow to get the BBOX of selected features in QGIS using the UI?Run QGIS layer Action on all selected featuresFeature Selection Using Custom Python Expression Functions in QGIS 2.18No “committedFeaturesAdded” signal after dataProvider().addFeatures() - QGiS 2.14.8Run QGIS Model on selected features only?Using file path in QgsVectorLayer?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I'm trying to migrate a python plugin I wrote from QGIS 2.18 to QGIS 3.4. In the plugin, I'm creating new vector features and eventually adding them to an existing vector layer. I'm trying to have the added features selected automatically in QGIS after running the code described below.
For QGIS 2.18, the QgsVectorLayer class had an addFeatures method that contained a very convenient makeSelected flag. When the flag was set to true, the added features were selected.



In QGIS 3.4 the addFeatures method still exists, but the flag is gone.
I also tried to select the features using some of the class's selection methods but with no success. It seems that after adding the features to the layer, their id's change and I don't have access to these specific features and can not select them using their old ids. The only way that somehow works is assigning some sentinel value to one of the fields in all the new features and then selecting them using a query. I'd like to avoid this way because I'm afraid that at some point it can mess up a user's data.



here's an example of how I created features and added them to the current selected layer in Qgis. it can be run in the Qgis Python terminal:



layer = iface.activeLayer()
layer.startEditing()
feat = QgsFeature(layer.fields())
point_list = [QgsPointXY(0, 0), QgsPointXY(0,1), QgsPointXY(1,1), QgsPointXY(1,0), QgsPointXY(0,0)]
feat.setGeometry(QgsGeometry.fromPolygonXY(point_list))
layer.addFeature(feat)

# I'd like to add feat to the layers selection at this point

self.layer.endEditCommand()




I'm using QGIS 3.4.1 (migrating from QGIS 2.18.26), and the pyqgis API of the above versions.



I'm aware that Qgis3 uses python 3 instead of python 2.










share|improve this question
























  • This script does not works in the QGIS Python terminal,

    – xunilk
    Jan 22 at 7:52











  • Hi xunik. Why did you change your comment? Your comment from before showed that the script did work for you in the Python terminal.

    – meir412
    Jan 22 at 9:00

















1















I'm trying to migrate a python plugin I wrote from QGIS 2.18 to QGIS 3.4. In the plugin, I'm creating new vector features and eventually adding them to an existing vector layer. I'm trying to have the added features selected automatically in QGIS after running the code described below.
For QGIS 2.18, the QgsVectorLayer class had an addFeatures method that contained a very convenient makeSelected flag. When the flag was set to true, the added features were selected.



In QGIS 3.4 the addFeatures method still exists, but the flag is gone.
I also tried to select the features using some of the class's selection methods but with no success. It seems that after adding the features to the layer, their id's change and I don't have access to these specific features and can not select them using their old ids. The only way that somehow works is assigning some sentinel value to one of the fields in all the new features and then selecting them using a query. I'd like to avoid this way because I'm afraid that at some point it can mess up a user's data.



here's an example of how I created features and added them to the current selected layer in Qgis. it can be run in the Qgis Python terminal:



layer = iface.activeLayer()
layer.startEditing()
feat = QgsFeature(layer.fields())
point_list = [QgsPointXY(0, 0), QgsPointXY(0,1), QgsPointXY(1,1), QgsPointXY(1,0), QgsPointXY(0,0)]
feat.setGeometry(QgsGeometry.fromPolygonXY(point_list))
layer.addFeature(feat)

# I'd like to add feat to the layers selection at this point

self.layer.endEditCommand()




I'm using QGIS 3.4.1 (migrating from QGIS 2.18.26), and the pyqgis API of the above versions.



I'm aware that Qgis3 uses python 3 instead of python 2.










share|improve this question
























  • This script does not works in the QGIS Python terminal,

    – xunilk
    Jan 22 at 7:52











  • Hi xunik. Why did you change your comment? Your comment from before showed that the script did work for you in the Python terminal.

    – meir412
    Jan 22 at 9:00













1












1








1


1






I'm trying to migrate a python plugin I wrote from QGIS 2.18 to QGIS 3.4. In the plugin, I'm creating new vector features and eventually adding them to an existing vector layer. I'm trying to have the added features selected automatically in QGIS after running the code described below.
For QGIS 2.18, the QgsVectorLayer class had an addFeatures method that contained a very convenient makeSelected flag. When the flag was set to true, the added features were selected.



In QGIS 3.4 the addFeatures method still exists, but the flag is gone.
I also tried to select the features using some of the class's selection methods but with no success. It seems that after adding the features to the layer, their id's change and I don't have access to these specific features and can not select them using their old ids. The only way that somehow works is assigning some sentinel value to one of the fields in all the new features and then selecting them using a query. I'd like to avoid this way because I'm afraid that at some point it can mess up a user's data.



here's an example of how I created features and added them to the current selected layer in Qgis. it can be run in the Qgis Python terminal:



layer = iface.activeLayer()
layer.startEditing()
feat = QgsFeature(layer.fields())
point_list = [QgsPointXY(0, 0), QgsPointXY(0,1), QgsPointXY(1,1), QgsPointXY(1,0), QgsPointXY(0,0)]
feat.setGeometry(QgsGeometry.fromPolygonXY(point_list))
layer.addFeature(feat)

# I'd like to add feat to the layers selection at this point

self.layer.endEditCommand()




I'm using QGIS 3.4.1 (migrating from QGIS 2.18.26), and the pyqgis API of the above versions.



I'm aware that Qgis3 uses python 3 instead of python 2.










share|improve this question
















I'm trying to migrate a python plugin I wrote from QGIS 2.18 to QGIS 3.4. In the plugin, I'm creating new vector features and eventually adding them to an existing vector layer. I'm trying to have the added features selected automatically in QGIS after running the code described below.
For QGIS 2.18, the QgsVectorLayer class had an addFeatures method that contained a very convenient makeSelected flag. When the flag was set to true, the added features were selected.



In QGIS 3.4 the addFeatures method still exists, but the flag is gone.
I also tried to select the features using some of the class's selection methods but with no success. It seems that after adding the features to the layer, their id's change and I don't have access to these specific features and can not select them using their old ids. The only way that somehow works is assigning some sentinel value to one of the fields in all the new features and then selecting them using a query. I'd like to avoid this way because I'm afraid that at some point it can mess up a user's data.



here's an example of how I created features and added them to the current selected layer in Qgis. it can be run in the Qgis Python terminal:



layer = iface.activeLayer()
layer.startEditing()
feat = QgsFeature(layer.fields())
point_list = [QgsPointXY(0, 0), QgsPointXY(0,1), QgsPointXY(1,1), QgsPointXY(1,0), QgsPointXY(0,0)]
feat.setGeometry(QgsGeometry.fromPolygonXY(point_list))
layer.addFeature(feat)

# I'd like to add feat to the layers selection at this point

self.layer.endEditCommand()




I'm using QGIS 3.4.1 (migrating from QGIS 2.18.26), and the pyqgis API of the above versions.



I'm aware that Qgis3 uses python 3 instead of python 2.







pyqgis vector-layer pyqgis-3 qgsvectorlayer






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 21 at 16:35









xunilk

14.9k31942




14.9k31942










asked Jan 20 at 15:02









meir412meir412

345




345












  • This script does not works in the QGIS Python terminal,

    – xunilk
    Jan 22 at 7:52











  • Hi xunik. Why did you change your comment? Your comment from before showed that the script did work for you in the Python terminal.

    – meir412
    Jan 22 at 9:00

















  • This script does not works in the QGIS Python terminal,

    – xunilk
    Jan 22 at 7:52











  • Hi xunik. Why did you change your comment? Your comment from before showed that the script did work for you in the Python terminal.

    – meir412
    Jan 22 at 9:00
















This script does not works in the QGIS Python terminal,

– xunilk
Jan 22 at 7:52





This script does not works in the QGIS Python terminal,

– xunilk
Jan 22 at 7:52













Hi xunik. Why did you change your comment? Your comment from before showed that the script did work for you in the Python terminal.

– meir412
Jan 22 at 9:00





Hi xunik. Why did you change your comment? Your comment from before showed that the script did work for you in the Python terminal.

– meir412
Jan 22 at 9:00










1 Answer
1






active

oldest

votes


















1














I've managed to reach the functionality I desired, and I'd like to share my solution.



I haven't found an elegant way to use the PyQGIS API to select the features you are adding to your layer, but I used the feature's geometry to track them down and add them to the selection.



I'm generalizing my solution to a list of features that you'd like to add to your layer and have them selected.
I'm assuming a list called geom_list which contains any number of QgsGeometry objects which represent the geometries of the features you're adding to your layer.



# prepare layer for editing
layer = iface.activeLayer()
layer.startEditing()
feature_list = []

# create all features with geometries from geom_list and fields from our layer and store in list
for index in range(len(geom_list)):
feat = QgsFeature(layer.fields())
feat.setGeometry(geom_list[index]]))
feature_list.append(feat)

# add new features to layer
layer.addFeatures(feature_list)

# Select all of the new added features
for general_feat in layer.getFeatures():
for desired_feat in feature_list:
if str(desired_feat.geometry()) == str(general_feat.geometry()):
layer.select(general_feat.id())

#finish editing
self.layer.endEditCommand()







share|improve this answer

























    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "79"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f309269%2fpython-scripting-in-qgis-to-add-features-and-select-them%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    I've managed to reach the functionality I desired, and I'd like to share my solution.



    I haven't found an elegant way to use the PyQGIS API to select the features you are adding to your layer, but I used the feature's geometry to track them down and add them to the selection.



    I'm generalizing my solution to a list of features that you'd like to add to your layer and have them selected.
    I'm assuming a list called geom_list which contains any number of QgsGeometry objects which represent the geometries of the features you're adding to your layer.



    # prepare layer for editing
    layer = iface.activeLayer()
    layer.startEditing()
    feature_list = []

    # create all features with geometries from geom_list and fields from our layer and store in list
    for index in range(len(geom_list)):
    feat = QgsFeature(layer.fields())
    feat.setGeometry(geom_list[index]]))
    feature_list.append(feat)

    # add new features to layer
    layer.addFeatures(feature_list)

    # Select all of the new added features
    for general_feat in layer.getFeatures():
    for desired_feat in feature_list:
    if str(desired_feat.geometry()) == str(general_feat.geometry()):
    layer.select(general_feat.id())

    #finish editing
    self.layer.endEditCommand()







    share|improve this answer





























      1














      I've managed to reach the functionality I desired, and I'd like to share my solution.



      I haven't found an elegant way to use the PyQGIS API to select the features you are adding to your layer, but I used the feature's geometry to track them down and add them to the selection.



      I'm generalizing my solution to a list of features that you'd like to add to your layer and have them selected.
      I'm assuming a list called geom_list which contains any number of QgsGeometry objects which represent the geometries of the features you're adding to your layer.



      # prepare layer for editing
      layer = iface.activeLayer()
      layer.startEditing()
      feature_list = []

      # create all features with geometries from geom_list and fields from our layer and store in list
      for index in range(len(geom_list)):
      feat = QgsFeature(layer.fields())
      feat.setGeometry(geom_list[index]]))
      feature_list.append(feat)

      # add new features to layer
      layer.addFeatures(feature_list)

      # Select all of the new added features
      for general_feat in layer.getFeatures():
      for desired_feat in feature_list:
      if str(desired_feat.geometry()) == str(general_feat.geometry()):
      layer.select(general_feat.id())

      #finish editing
      self.layer.endEditCommand()







      share|improve this answer



























        1












        1








        1







        I've managed to reach the functionality I desired, and I'd like to share my solution.



        I haven't found an elegant way to use the PyQGIS API to select the features you are adding to your layer, but I used the feature's geometry to track them down and add them to the selection.



        I'm generalizing my solution to a list of features that you'd like to add to your layer and have them selected.
        I'm assuming a list called geom_list which contains any number of QgsGeometry objects which represent the geometries of the features you're adding to your layer.



        # prepare layer for editing
        layer = iface.activeLayer()
        layer.startEditing()
        feature_list = []

        # create all features with geometries from geom_list and fields from our layer and store in list
        for index in range(len(geom_list)):
        feat = QgsFeature(layer.fields())
        feat.setGeometry(geom_list[index]]))
        feature_list.append(feat)

        # add new features to layer
        layer.addFeatures(feature_list)

        # Select all of the new added features
        for general_feat in layer.getFeatures():
        for desired_feat in feature_list:
        if str(desired_feat.geometry()) == str(general_feat.geometry()):
        layer.select(general_feat.id())

        #finish editing
        self.layer.endEditCommand()







        share|improve this answer















        I've managed to reach the functionality I desired, and I'd like to share my solution.



        I haven't found an elegant way to use the PyQGIS API to select the features you are adding to your layer, but I used the feature's geometry to track them down and add them to the selection.



        I'm generalizing my solution to a list of features that you'd like to add to your layer and have them selected.
        I'm assuming a list called geom_list which contains any number of QgsGeometry objects which represent the geometries of the features you're adding to your layer.



        # prepare layer for editing
        layer = iface.activeLayer()
        layer.startEditing()
        feature_list = []

        # create all features with geometries from geom_list and fields from our layer and store in list
        for index in range(len(geom_list)):
        feat = QgsFeature(layer.fields())
        feat.setGeometry(geom_list[index]]))
        feature_list.append(feat)

        # add new features to layer
        layer.addFeatures(feature_list)

        # Select all of the new added features
        for general_feat in layer.getFeatures():
        for desired_feat in feature_list:
        if str(desired_feat.geometry()) == str(general_feat.geometry()):
        layer.select(general_feat.id())

        #finish editing
        self.layer.endEditCommand()








        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Apr 11 at 19:10

























        answered Apr 11 at 15:21









        meir412meir412

        345




        345



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Geographic Information Systems Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f309269%2fpython-scripting-in-qgis-to-add-features-and-select-them%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            រឿង រ៉ូមេអូ និង ហ្ស៊ុយលីយេ សង្ខេបរឿង តួអង្គ បញ្ជីណែនាំ

            Crop image to path created in TikZ? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Crop an inserted image?TikZ pictures does not appear in posterImage behind and beyond crop marks?Tikz picture as large as possible on A4 PageTransparency vs image compression dilemmaHow to crop background from image automatically?Image does not cropTikzexternal capturing crop marks when externalizing pgfplots?How to include image path that contains a dollar signCrop image with left size given

            Romeo and Juliet ContentsCharactersSynopsisSourcesDate and textThemes and motifsCriticism and interpretationLegacyScene by sceneSee alsoNotes and referencesSourcesExternal linksNavigation menu"Consumer Price Index (estimate) 1800–"10.2307/28710160037-3222287101610.1093/res/II.5.31910.2307/45967845967810.2307/2869925286992510.1525/jams.1982.35.3.03a00050"Dada Masilo: South African dancer who breaks the rules"10.1093/res/os-XV.57.1610.2307/28680942868094"Sweet Sorrow: Mann-Korman's Romeo and Juliet Closes Sept. 5 at MN's Ordway"the original10.2307/45957745957710.1017/CCOL0521570476.009"Ram Leela box office collections hit massive Rs 100 crore, pulverises prediction"Archived"Broadway Revival of Romeo and Juliet, Starring Orlando Bloom and Condola Rashad, Will Close Dec. 8"Archived10.1075/jhp.7.1.04hon"Wherefore art thou, Romeo? To make us laugh at Navy Pier"the original10.1093/gmo/9781561592630.article.O006772"Ram-leela Review Roundup: Critics Hail Film as Best Adaptation of Romeo and Juliet"Archived10.2307/31946310047-77293194631"Romeo and Juliet get Twitter treatment""Juliet's Nurse by Lois Leveen""Romeo and Juliet: Orlando Bloom's Broadway Debut Released in Theaters for Valentine's Day"Archived"Romeo and Juliet Has No Balcony"10.1093/gmo/9781561592630.article.O00778110.2307/2867423286742310.1076/enst.82.2.115.959510.1080/00138380601042675"A plague o' both your houses: error in GCSE exam paper forces apology""Juliet of the Five O'Clock Shadow, and Other Wonders"10.2307/33912430027-4321339124310.2307/28487440038-7134284874410.2307/29123140149-661129123144728341M"Weekender Guide: Shakespeare on The Drive""balcony"UK public library membership"romeo"UK public library membership10.1017/CCOL9780521844291"Post-Zionist Critique on Israel and the Palestinians Part III: Popular Culture"10.2307/25379071533-86140377-919X2537907"Capulets and Montagues: UK exam board admit mixing names up in Romeo and Juliet paper"Istoria Novellamente Ritrovata di Due Nobili Amanti2027/mdp.390150822329610820-750X"GCSE exam error: Board accidentally rewrites Shakespeare"10.2307/29176390149-66112917639"Exam board apologises after error in English GCSE paper which confused characters in Shakespeare's Romeo and Juliet""From Mariotto and Ganozza to Romeo and Guilietta: Metamorphoses of a Renaissance Tale"10.2307/37323537323510.2307/2867455286745510.2307/28678912867891"10 Questions for Taylor Swift"10.2307/28680922868092"Haymarket Theatre""The Zeffirelli Way: Revealing Talk by Florentine Director""Michael Smuin: 1938-2007 / Prolific dance director had showy career"The Life and Art of Edwin BoothRomeo and JulietRomeo and JulietRomeo and JulietRomeo and JulietEasy Read Romeo and JulietRomeo and Julieteeecb12003684p(data)4099369-3n8211610759dbe00d-a9e2-41a3-b2c1-977dd692899302814385X313670221313670221