Add a menu to sliceController

Hi. This is my code to add a menu to the Red Slice controller:

toolButton = qt.QToolButton()

toolButton = qt.QToolButton()
toolButton.setText('T')
slicer.app.layoutManager().sliceWidget("Red").sliceController().barLayout().insertWidget(0,toolButton)

myMenu = qt.QMenu(toolButton)
toolButton.setMenu(myMenu)

pushButton = qt.QPushButton('mybutton')
widgetAction = qt.QWidgetAction(myMenu)
widgetAction.setDefaultWidget(pushButton)

myMenu.addAction(widgetAction)
myMenu.addAction("testAction")

It doesn’t work. The actions do not show when you click the toolButton. Could you help?

The default popup mode is DelayedPopup for a QToolButton. I believe you have missed this as showing the action does work with your code when long pressing on the toolbutton.
image

# Create ToolButton and add to sliceController
toolButton = qt.QToolButton()
slicer.app.layoutManager().sliceWidget("Red").sliceController().barLayout().insertWidget(0,toolButton)
# Create QMenu and add QActions to it
myMenu = qt.QMenu(toolButton)
myActionT = qt.QAction("T")
myActionTest = qt.QAction("Test")
myMenu.addAction(myActionT)
myMenu.addAction(myActionTest)
# Add Menu to ToolButton
toolButton.setMenu(myMenu)
# Want to define one of the menu items so it is triggered on toolbutton press? set it as default action
toolButton.setDefaultAction(myActionT)

# Default to show menu is DelayedPopup method which requires long press
# Long press is to differentiate it from pressing ToolButton (the default QAction)

# Want a different method to show menu?
# Other options include arrow next to button to open menu
toolButton.setPopupMode(qt.QToolButton.MenuButtonPopup)
# Open the menu by clicking the toolbutton rather than triggering the default QAction
toolButton.setPopupMode(qt.QToolButton.InstantPopup)
1 Like