Mouse click over slice

By default, in markup widgets RightButtonClickEvent interaction event is translated to WidgetEventMenu widget event, which displays a context menu. You can remove the old mapping and add a new mapping to a custom event using widget.SetEventTranslation (see examples in the script repository).

For example, you can translate the right-click event to slicer.vtkSlicerMarkupsWidget.WidgetEventCustomAction1 event, which invokes a slicer.vtkMRMLMarkupsDisplayNode.CustomActionEvent1 on the markup’s display node. To get notified about the right-click event you just need to add an observer to this event.

Example:

def someCustomAction(caller, eventId):
  markupsDisplayNode = caller
  print(f"Custom action activated in {markupsDisplayNode.GetName()}")

views = [
    slicer.app.layoutManager().threeDWidget(0).threeDView(),
    slicer.app.layoutManager().sliceWidget("Red").sliceView(),
    slicer.app.layoutManager().sliceWidget("Yellow").sliceView(),
    slicer.app.layoutManager().sliceWidget("Green").sliceView()
]

observations = []  # store the observations so that later can be removed
markupsDisplayNodes = slicer.util.getNodesByClass("vtkMRMLMarkupsDisplayNode")
for markupsDisplayNode in markupsDisplayNodes:
    # Add observer to custom actions
    observations.append([markupsDisplayNode, markupsDisplayNode.AddObserver(markupsDisplayNode.CustomActionEvent1, someCustomAction)])
    for view in views:
        markupsDisplayableManager = view.displayableManagerByClassName('vtkMRMLMarkupsDisplayableManager')
        # Assign keyboard shortcut to trigger custom actions
        widget = markupsDisplayableManager.GetWidget(markupsDisplayNode)
        # Remove old event translation
        widget.SetEventTranslation(widget.WidgetStateOnWidget, slicer.vtkMRMLInteractionEventData.RightButtonClickEvent, vtk.vtkEvent.NoModifier, vtk.vtkWidgetEvent.NoEvent)
        # Add new event translation
        widget.SetEventTranslation(widget.WidgetStateOnWidget, slicer.vtkMRMLInteractionEventData.RightButtonClickEvent, vtk.vtkEvent.NoModifier, widget.WidgetEventCustomAction1)

## Remove observations when custom actions are not needed anymore by uncommenting these lines:
# for observedNode, observation in observations:
#     observedNode.RemoveObserver(observation)
1 Like