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 afterstartEditing()
which, by default, finishes the editing command if the commit is successful. To avoid this behavior, you can pass aFalse
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 callstopEditing()
.Working code: