〇環境
・Windows11PC
・Blender4.1
〇ショートカットの変更
Blenderでショートカットキーの変更を行うためにはプリファレンスのキーマップに登録することが一般的です。

〇アドオンの基礎
以下のコードはBlenderアドオンの基礎部分になります。
import bpy
# オペレーターを定義
class SimpleOperator(bpy.types.Operator):
bl_idname = "wm.simple_operator"
bl_label = "Simple Operator"
def execute(self, context):
print("ショートカットキーが押されました!")
return {'FINISHED'}
ここでは機能であるオペレータを定義しています。
次に、3Dビューポートのサイドバーに「Custom Keymap」というタブを追加します。
class VIEW3D_PT_CustomKeymapMenu(bpy.types.Panel):
bl_label = "Custom Keymap Settings"
bl_idname = "VIEW3D_PT_custom_keymap_menu"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = "Custom Keymap"
def draw(self, context):
layout = self.layout
layout.label(text="Configure your custom shortcut:")
layout.operator("screen.userpref_show", text="Open Keymap Preferences")
これを定義することで3Dビューポート上にメニューが使用可能となります。

ここではOpen Keymap Preferencesというボタンを定義しています。
次にショートカットキーを定義します。
ここではCtrl+Oキーで機能するキーを定義しました。
この定義時にkyemapに登録する形で定義することでKeymapウィンドウから任意に変更可能としています。
def register():
bpy.utils.register_class(SimpleOperator)
bpy.utils.register_class(VIEW3D_PT_CustomKeymapMenu)
wm = bpy.context.window_manager
kc = wm.keyconfigs.addon
if kc:
km = kc.keymaps.new(name="3D View", space_type='VIEW_3D')
km.keymap_items.new(
idname=SimpleOperator.bl_idname,
type='O,
value='PRESS',
ctrl=True
)
このコードを実行した状態で3DビューポートでCtrl+Oキーを押すとコンソールにログが出力されます。

また3Dビューポートのメニューにはプリファレンスを開くボタンが表示されKeymapの検索欄でSimple Operatorと検索することでキーの任意変更が可能になります。


以上でBlenderPythonで任意のショートカットキーで実行可能な処理を実装できました。
今後ショートカットキーを含むアドオンを開発する際にKeymapを経由して登録できるようにすると便利そうです。
〇コード全文
import bpy
# オペレーターを定義
class SimpleOperator(bpy.types.Operator):
bl_idname = "wm.simple_operator"
bl_label = "Simple Operator"
def execute(self, context):
print("ショートカットキーが押されました!")
return {'FINISHED'}
# 3Dビューポートのメニューに登録するクラス
class VIEW3D_PT_CustomKeymapMenu(bpy.types.Panel):
bl_label = "Custom Keymap Settings"
bl_idname = "VIEW3D_PT_custom_keymap_menu"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = "Custom Keymap"
def draw(self, context):
layout = self.layout
layout.label(text="Configure your custom shortcut:")
layout.operator("screen.userpref_show", text="Open Keymap Preferences")
def register():
bpy.utils.register_class(SimpleOperator)
bpy.utils.register_class(VIEW3D_PT_CustomKeymapMenu)
wm = bpy.context.window_manager
kc = wm.keyconfigs.addon
if kc:
km = kc.keymaps.new(name="3D View", space_type='VIEW_3D')
km.keymap_items.new(
idname=SimpleOperator.bl_idname,
type='A',
value='PRESS',
ctrl=True
)
def unregister():
bpy.utils.unregister_class(SimpleOperator)
bpy.utils.unregister_class(VIEW3D_PT_CustomKeymapMenu)
wm = bpy.context.window_manager
kc = wm.keyconfigs.addon
if kc:
km = kc.keymaps.get("3D View")
if km:
for kmi in km.keymap_items:
if kmi.idname == SimpleOperator.bl_idname:
km.keymap_items.remove(kmi)
if __name__ == "__main__":
register()