The system of keymap preference in Blender is complex a little.
GOAL
Today’s goal is to summarize how to customize keymaps in Blender. The main contents are how to change keymaps, save and import/export key configuration presets. This article doesn’t contain how to use keymap editor or details of UI.
Environment
Blender 2.83 (Python 3.7.4) Windows 10
What is keymap preference?
The following is an excerpt from the Blender manual.
The keymap editor lets you adjust your keymap via:
Presets: Predefined keymaps which come with Blender and can be added to. Preferences: Keymaps may define their own preferences to change the functionality or add additional key bindings. Key Map Items: You may add/remove/edit individual keymap entries.
def get_keyconfigs():
"""
:return: dict{kerconfig_name(str): path to config file(str)}
"""
config_pathes = bpy.utils.preset_paths("keyconfig")
config_dict = {}
for config_path in config_pathes:
for file in os.listdir(config_path):
name, ext = os.path.splitext(file)
if ext.lower() in [".py", ".xml"] and not name[0] == ".":
config_dict[name] = os.path.join(config_path, file)
return config_dict
2.2 Activate specified keyconfig and return active keyconfig
Activate the specified keyconfig by its path and get active keyconfig with wm.keyconfigs.active then restore active keyconfig to original settings.
def get_keyconfig(keyconfig_name, keyconfig_dict):
wm = bpy.context.window_manager
if keyconfig_name in wm.keyconfigs.keys(): #if the keyconfig can be found, return it
return wm.keyconfigs[keyconfig_name]
else: # activate by config path and return it
keyconfig_path = keyconfig_dict[keyconfig_name]
current_path = keyconfig_dict[wm.keyconfigs.active.name]
bpy.ops.preferences.keyconfig_activate(filepath=keyconfig_path)
kc = wm.keyconfigs.active
bpy.ops.preferences.keyconfig_activate(filepath=current_path)
return kc
When I activate my addon that uses operations with bpy.ops in register() function, the error “AttributeError: ‘_RestrictContext’ object has no attribute ‘view_layer’ ” occurred.