TransWikia.com

Make QGIS wait in for loop on condition

Geographic Information Systems Asked on August 13, 2021

The goal is to check whether the user has added a point to a layer, and wait until then

Unfortunately, using QtGui.QApplication.processEvents() did not suffice.

time.sleep() inside a while loop on condition does not work, since QGIS will freeze its own Python engine with time.sleep

This is my best effort:

from qgis.core import QgsVectorLayer

# create layer
points_layer = QgsVectorLayer("Point", "temporary_points", "memory")
QgsProject.instance().addMapLayer(points_layer)

# get feature coint in points layer before editing
count_before_editing = points_layer.featureCount()
print("count_before_editing", count_before_editing)

# check wether the layer is editable
if not points_layer.isEditable():
    #make it editable
    points_layer.startEditing()
    # check if the requestet point feature has been set
    while points_layer.featureCount()<count_before_editing+1:
        print(points_layer.featureCount())
        # here i am missing the functionality to wait, while I manually add a point to the points layer
        #break is only here, to prevent your qgis from remaining in while
        break
    # stop editing and commit changes
    points_layer.commitChanges()

One Answer

Not sure you are choosing the "right" approach. You would better use Qt signals to catch changes in the layer.

from qgis.core import QgsVectorLayer

# create layer
points_layer = QgsVectorLayer("Point", "temporary_points", "memory")
QgsProject.instance().addMapLayer(points_layer)

def featureAdded(featureid):
    print(points_layer.getFeature(featureid))

# Signal will be executed without caring about if feature added has been committed
points_layer.featureAdded.connect(featureAdded)

def committedFeaturesAdded(layerId, featureList):
    print(layerId, featureList) 

# Signal will be executed only after committed
points_layer.committedFeaturesAdded.connect(committedFeaturesAdded)

Answered by ThomasG77 on August 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP