1

I need to write scripts to set shortcuts for Toggle Editing, Save Editing, and Pan. I am using QGIS 3.16. Here is the code I used to set shortcut for Toggle Editing, there is no errors when I run it. But it's not working

def Ed():
    layer = iface.activeLayer()
    if not layer.isEditable():
        layer.startEditing()
        layer.commitChanges()
    else:
        layer.commitChanges()
        layer.stopEditing()
    
from qgis.PyQt.QtGui import QKeySequence
from qgis.PyQt.QtWidgets import QShortcut
from qgis.PyQt.QtCore import Qt
shortcut = QShortcut(QKeySequence(Qt.Key_E), iface.mainWindow())
shortcut.setContext(Qt.ApplicationShortcut)
shortcut.activated.connect(Ed)

1 Answer 1

4

Your code doesn't work because you call layer.commitChanges() immediately after startEditing() which, by default, finishes the editing command if the commit is successful. To avoid this behavior, you can pass a False argument which will keep the layer in edit mode or alternatively remove the command altogether. Additionally, this means that in your else clause, you don't need to call stopEditing().

Working code:

def Ed():
    layer = iface.activeLayer()
    if not layer.isEditable():
        layer.startEditing()
        #line below is optional...
        #layer.commitChanges(False)
    else:
        layer.commitChanges()
    
from qgis.PyQt.QtGui import QKeySequence
from qgis.PyQt.QtWidgets import QShortcut
from qgis.PyQt.QtCore import Qt
shortcut = QShortcut(QKeySequence(Qt.Key_E), iface.mainWindow())
shortcut.setContext(Qt.ApplicationShortcut)
shortcut.activated.connect(Ed)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.