PyQGIS Editing – Set Shortcut for ToggleEditing, Save Editing, and Pan in QGIS Python

editingpyqgis

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)

Best Answer

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)
Related Question