Add a custom widget to a layout

I tried this code to make a custom layout (with a custom widget) for a scripted module and it doesn’t work:

    #get custom layout widgets
    containingListWidget = slicer.util.loadUI(self.resourcePath('UI/containingListWidget.ui'))
    self.containingListUI = slicer.util.childWidgetVariables(containingListWidget)
    slicer.mrmlScene.AddDefaultNode(containingListWidget)

    # Set scene in MRML widgets. Make sure that in Qt designer the top-level qMRMLWidget's
    # "mrmlSceneChanged(vtkMRMLScene*)" signal in is connected to each MRML widget's.
    # "setMRMLScene(vtkMRMLScene*)" slot.
    containingListWidget.setMRMLScene(slicer.mrmlScene)

    customLayout = """
    <layout type="vertical">
      <item>
      <widget class="listFrame">
      </widget>
      </item>
      <item>
    </layout>
    """

It brings up this error:

slicer.mrmlScene.AddDefaultNode(availableVersionsWidget)
TypeError: AddDefaultNode argument 1: method requires a VTK object

Could you help?

The error is because loadUI creates a QWiget, not a vtkMRMLNode.

Custom widgets can be added to view layouts using qSlicerSingletonViewFactory:

containingListWidget = slicer.util.loadUI(self.resourcePath('UI/containingListWidget.ui'))
self.containingListUI = slicer.util.childWidgetVariables(containingListWidget)
containingListWidget.setMRMLScene(slicer.mrmlScene)

viewFactory = slicer.qSlicerSingletonViewFactory()
viewFactory.setTagName("listWidget")
viewFactory.setWidget(containingListWidget)
slicer.app.layoutManager().registerViewFactory(viewFactory)

layout = """
<layout type=\"horizontal\">
  <item>
    <listWidget></listWidget>
  </item>
</layout>"""
layoutId = 1234

layoutNode = slicer.app.layoutManager().layoutLogic().GetLayoutNode()
layoutNode.AddLayoutDescription(
  layoutId, layout)

slicer.app.layoutManager().setLayout(layoutId)

-Thank youas gdfdgfddfhffd

1 Like