Skip to content

napari_cellseg3d.interface

User interface functions and aliases.

Classes:

Name Description
AnisotropyWidgets

Class that creates widgets for anisotropy handling.

Button

Class for a button with a title and connected to a function when clicked. Inherits from QPushButton.

CheckBox

Shortcut class for creating QCheckBox with a title and a function.

ContainerWidget

Class for a container widget that can contain other widgets.

DoubleIncrementCounter

Class implementing a number counter with increments (spin box) for floats.

DropdownMenu

Creates a dropdown menu with a title and adds specified entries to it.

FilePathWidget

Widget to handle the choice of file paths for data throughout the plugin.

GroupedWidget

Subclass of QGroupBox designed to easily group widgets belonging to a same category.

IntIncrementCounter

Class implementing a number counter with increments (spin box) for int.

LayerSelecter

Class that creates a dropdown menu to select a layer from a napari viewer.

Log

Class to implement a log for important user info. Should be thread-safe.

QWidgetSingleton

To be used as a metaclass when making a singleton QWidget, meaning only one instance exists at a time.

RadioButton

Class for a radio button with a title and connected to a function when clicked. Inherits from QRadioButton.

ScrollArea

Creates a QScrollArea and sets it up, then adds the contained_layout to it.

Slider

Shortcut class to create a Slider widget.

UtilsDropdown

Singleton class for use in instantiating only one Utility dropdown menu that can be accessed from the plugin.

Functions:

Name Description
add_blank

Adds a space between consecutive buttons/labels in a layout when building a widget.

add_label

Adds a label to a widget.

add_widgets

Adds all widgets in the list to layout, with the specified alignment.

combine_blocks

Combines two QWidget objects and puts them side by side (first on the left/top and second on the right/bottom depending on "horizontal").

handle_adjust_errors

Qt message handler that attempts to react to errors when setting the window size and resizes the main window.

handle_adjust_errors_wrapper

Returns a callable that can be used with qInstallMessageHandler directly.

make_group

Creates a group widget and layout, with a header (title) and content margins for top/left/right/bottom L, T, R, B (in pixels).

make_label

Creates a QLabel.

make_n_spinboxes

Creates n increment counters with the specified parameters.

open_directory

Opens a folder in the OS file browser.

open_file_dialog

Opens a window to choose a file directory using QFileDialog.

open_folder_dialog

Opens a window to choose a directory using QFileDialog.

open_url

Opens the url given as a string in OS default browser using :py:func:QDesktopServices.openUrl.

set_hover_color

Makes a push button glow with color while hovered; other states keep the napari theme.

set_spinbox

Sets the parameters of a QSpinBox or QDoubleSpinBox.

toggle_visibility

Toggles the visibility of a widget based on the status of a checkbox.

Attributes:

Name Type Description
ABS_AL

Alias for Qt.AlignmentFlag.AlignAbsolute, to use in addWidget

BOTT_AL

Alias for Qt.AlignmentFlag.AlignBottom, to use in addWidget

CENTER_AL

Alias for Qt.AlignmentFlag.AlignCenter, to use in addWidget

HCENTER_AL

Alias for Qt.AlignmentFlag.AlignHCenter, to use in addWidget

LEFT_AL

Alias for Qt.AlignmentFlag.AlignLeft, to use in addWidget

RIGHT_AL

Alias for Qt.AlignmentFlag.AlignRight, to use in addWidget

TOP_AL

Alias for Qt.AlignmentFlag.AlignTop, to use in addWidget

ABS_AL module-attribute

ABS_AL = Qt.AlignmentFlag.AlignAbsolute

Alias for Qt.AlignmentFlag.AlignAbsolute, to use in addWidget

BOTT_AL module-attribute

BOTT_AL = Qt.AlignmentFlag.AlignBottom

Alias for Qt.AlignmentFlag.AlignBottom, to use in addWidget

CENTER_AL module-attribute

CENTER_AL = Qt.AlignmentFlag.AlignCenter

Alias for Qt.AlignmentFlag.AlignCenter, to use in addWidget

HCENTER_AL module-attribute

HCENTER_AL = Qt.AlignmentFlag.AlignHCenter

Alias for Qt.AlignmentFlag.AlignHCenter, to use in addWidget

LEFT_AL module-attribute

LEFT_AL = Qt.AlignmentFlag.AlignLeft

Alias for Qt.AlignmentFlag.AlignLeft, to use in addWidget

RIGHT_AL module-attribute

RIGHT_AL = Qt.AlignmentFlag.AlignRight

Alias for Qt.AlignmentFlag.AlignRight, to use in addWidget

TOP_AL module-attribute

TOP_AL = Qt.AlignmentFlag.AlignTop

Alias for Qt.AlignmentFlag.AlignTop, to use in addWidget

AnisotropyWidgets

Bases: QWidget

Class that creates widgets for anisotropy handling.

Includes

A checkbox to hides or shows the controls Three spinboxes to enter resolution for each dimension.

Methods:

Name Description
__init__

Creates an instance of AnisotropyWidgets.

anisotropy_zoom_factor

Computes a zoom factor to correct anisotropy, based on anisotropy resolutions.

build

Builds the layout of the widget.

enabled

Returns : whether anisotropy correction has been enabled or not.

resolution_xyz

The resolution selected for each of the three dimensions. XYZ order (for MONAI).

resolution_zyx

The resolution selected for each of the three dimensions. ZYX order (for napari).

scaling_xyz

The scaling factors for each of the three dimensions. XYZ order (for MONAI).

scaling_zyx

The scaling factors for each of the three dimensions. ZYX order (for napari).

Source code in napari_cellseg3d/interface.py
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
class AnisotropyWidgets(QWidget):
    """Class that creates widgets for anisotropy handling.

    Includes :
        A checkbox to hides or shows the controls
        Three spinboxes to enter resolution for each dimension.
    """

    def __init__(
        self,
        parent: Optional[QWidget] = None,
        default_x: Optional[float] = 1.0,
        default_y: Optional[float] = 1.0,
        default_z: Optional[float] = 1.0,
        always_visible: Optional[bool] = False,
        use_integer_counter: Optional[bool] = False,
    ):
        """Creates an instance of AnisotropyWidgets.

        Args:
            parent: parent QWidget
            default_x: default resolution to use for x axis in microns
            default_y: default resolution to use for y axis in microns
            default_z: default resolution to use for z axis in microns
            always_visible: if True, the checkbox is hidden and the spinboxes are always visible
            use_integer_counter: if True, the spinboxes are QSpinBoxes instead of QDoubleSpinBoxes
        """
        super().__init__(parent)

        self._layout = QVBoxLayout()
        self._layout.setSpacing(0)
        self._layout.setContentsMargins(0, 0, 0, 0)

        self.container = ContainerWidget(t=7, parent=parent)
        self.checkbox = CheckBox("Anisotropic data", self._toggle_display_aniso, parent)

        if use_integer_counter:
            self.box_widgets = IntIncrementCounter.make_n(
                n=3, lower=1, upper=9999, default=64, step=1
            )
        else:
            self.box_widgets = DoubleIncrementCounter.make_n(
                n=3, lower=1.0, upper=1000.0, default=1.0, step=0.5
            )
        self.box_widgets[0].setValue(default_x)
        self.box_widgets[1].setValue(default_y)
        self.box_widgets[2].setValue(default_z)

        for w in self.box_widgets:
            w.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        self.box_widgets_lbl = [
            make_label("Pixel size in " + axis + " (microns) :", parent=parent)
            for axis in "xyz"
        ]

        ##################
        # tooltips
        self.checkbox.setToolTip(
            "If you have anisotropic data, you can scale data using your resolution in microns"
        )
        [
            w.setToolTip(f"Anisotropic resolution in microns for {dim} axis")
            for w, dim in zip(self.box_widgets, "xyz", strict=False)
        ]
        ##################

        self.build()

        if always_visible:
            self._toggle_permanent_visibility()

    def _toggle_display_aniso(self):
        """Shows the choices for correcting anisotropy when viewing results depending on whether :py:attr:`self.checkbox` is checked."""
        toggle_visibility(self.checkbox, self.container)

    def build(self):
        """Builds the layout of the widget."""
        [
            self.container.layout.addWidget(widget, alignment=HCENTER_AL)
            for widgets in zip(self.box_widgets_lbl, self.box_widgets, strict=False)
            for widget in widgets
        ]
        # anisotropy
        self.container.setLayout(self.container.layout)
        self.container.setVisible(False)

        add_widgets(self._layout, [self.checkbox, self.container])
        self.setLayout(self._layout)

    def resolution_xyz(self):
        """The resolution selected for each of the three dimensions. XYZ order (for MONAI)."""
        return [w.value() for w in self.box_widgets]

    def scaling_xyz(self):
        """The scaling factors for each of the three dimensions. XYZ order (for MONAI)."""
        return self.anisotropy_zoom_factor(self.resolution_xyz())

    def resolution_zyx(self):
        """The resolution selected for each of the three dimensions. ZYX order (for napari)."""
        res = self.resolution_xyz()
        return [res[2], res[1], res[0]]

    def scaling_zyx(self):
        """The scaling factors for each of the three dimensions. ZYX order (for napari)."""
        return self.anisotropy_zoom_factor(self.resolution_zyx())

    @staticmethod
    def anisotropy_zoom_factor(aniso_res):
        """Computes a zoom factor to correct anisotropy, based on anisotropy resolutions.

        Args:
            aniso_res: array for anisotropic resolution (float) in microns for each axis

        Returns: an array with the corresponding zoom factors for each axis (all values divided by min)

        """
        base = min(aniso_res)
        return [base / res for res in aniso_res]

    def enabled(self):
        """Returns : whether anisotropy correction has been enabled or not."""
        return self.checkbox.isChecked()

    def _toggle_permanent_visibility(self):
        """Hides the checkbox and always display resolution spinboxes."""
        self.checkbox.toggle()
        self.checkbox.setVisible(False)

__init__

__init__(parent: Optional[QWidget] = None, default_x: Optional[float] = 1.0, default_y: Optional[float] = 1.0, default_z: Optional[float] = 1.0, always_visible: Optional[bool] = False, use_integer_counter: Optional[bool] = False)

Creates an instance of AnisotropyWidgets.

Parameters:

Name Type Description Default
parent Optional[QWidget]

parent QWidget

None
default_x Optional[float]

default resolution to use for x axis in microns

1.0
default_y Optional[float]

default resolution to use for y axis in microns

1.0
default_z Optional[float]

default resolution to use for z axis in microns

1.0
always_visible Optional[bool]

if True, the checkbox is hidden and the spinboxes are always visible

False
use_integer_counter Optional[bool]

if True, the spinboxes are QSpinBoxes instead of QDoubleSpinBoxes

False
Source code in napari_cellseg3d/interface.py
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
def __init__(
    self,
    parent: Optional[QWidget] = None,
    default_x: Optional[float] = 1.0,
    default_y: Optional[float] = 1.0,
    default_z: Optional[float] = 1.0,
    always_visible: Optional[bool] = False,
    use_integer_counter: Optional[bool] = False,
):
    """Creates an instance of AnisotropyWidgets.

    Args:
        parent: parent QWidget
        default_x: default resolution to use for x axis in microns
        default_y: default resolution to use for y axis in microns
        default_z: default resolution to use for z axis in microns
        always_visible: if True, the checkbox is hidden and the spinboxes are always visible
        use_integer_counter: if True, the spinboxes are QSpinBoxes instead of QDoubleSpinBoxes
    """
    super().__init__(parent)

    self._layout = QVBoxLayout()
    self._layout.setSpacing(0)
    self._layout.setContentsMargins(0, 0, 0, 0)

    self.container = ContainerWidget(t=7, parent=parent)
    self.checkbox = CheckBox("Anisotropic data", self._toggle_display_aniso, parent)

    if use_integer_counter:
        self.box_widgets = IntIncrementCounter.make_n(
            n=3, lower=1, upper=9999, default=64, step=1
        )
    else:
        self.box_widgets = DoubleIncrementCounter.make_n(
            n=3, lower=1.0, upper=1000.0, default=1.0, step=0.5
        )
    self.box_widgets[0].setValue(default_x)
    self.box_widgets[1].setValue(default_y)
    self.box_widgets[2].setValue(default_z)

    for w in self.box_widgets:
        w.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

    self.box_widgets_lbl = [
        make_label("Pixel size in " + axis + " (microns) :", parent=parent)
        for axis in "xyz"
    ]

    ##################
    # tooltips
    self.checkbox.setToolTip(
        "If you have anisotropic data, you can scale data using your resolution in microns"
    )
    [
        w.setToolTip(f"Anisotropic resolution in microns for {dim} axis")
        for w, dim in zip(self.box_widgets, "xyz", strict=False)
    ]
    ##################

    self.build()

    if always_visible:
        self._toggle_permanent_visibility()

anisotropy_zoom_factor staticmethod

anisotropy_zoom_factor(aniso_res)

Computes a zoom factor to correct anisotropy, based on anisotropy resolutions.

Parameters:

Name Type Description Default
aniso_res

array for anisotropic resolution (float) in microns for each axis

required

Returns: an array with the corresponding zoom factors for each axis (all values divided by min)

Source code in napari_cellseg3d/interface.py
761
762
763
764
765
766
767
768
769
770
771
772
@staticmethod
def anisotropy_zoom_factor(aniso_res):
    """Computes a zoom factor to correct anisotropy, based on anisotropy resolutions.

    Args:
        aniso_res: array for anisotropic resolution (float) in microns for each axis

    Returns: an array with the corresponding zoom factors for each axis (all values divided by min)

    """
    base = min(aniso_res)
    return [base / res for res in aniso_res]

build

build()

Builds the layout of the widget.

Source code in napari_cellseg3d/interface.py
730
731
732
733
734
735
736
737
738
739
740
741
742
def build(self):
    """Builds the layout of the widget."""
    [
        self.container.layout.addWidget(widget, alignment=HCENTER_AL)
        for widgets in zip(self.box_widgets_lbl, self.box_widgets, strict=False)
        for widget in widgets
    ]
    # anisotropy
    self.container.setLayout(self.container.layout)
    self.container.setVisible(False)

    add_widgets(self._layout, [self.checkbox, self.container])
    self.setLayout(self._layout)

enabled

enabled()

Returns : whether anisotropy correction has been enabled or not.

Source code in napari_cellseg3d/interface.py
774
775
776
def enabled(self):
    """Returns : whether anisotropy correction has been enabled or not."""
    return self.checkbox.isChecked()

resolution_xyz

resolution_xyz()

The resolution selected for each of the three dimensions. XYZ order (for MONAI).

Source code in napari_cellseg3d/interface.py
744
745
746
def resolution_xyz(self):
    """The resolution selected for each of the three dimensions. XYZ order (for MONAI)."""
    return [w.value() for w in self.box_widgets]

resolution_zyx

resolution_zyx()

The resolution selected for each of the three dimensions. ZYX order (for napari).

Source code in napari_cellseg3d/interface.py
752
753
754
755
def resolution_zyx(self):
    """The resolution selected for each of the three dimensions. ZYX order (for napari)."""
    res = self.resolution_xyz()
    return [res[2], res[1], res[0]]

scaling_xyz

scaling_xyz()

The scaling factors for each of the three dimensions. XYZ order (for MONAI).

Source code in napari_cellseg3d/interface.py
748
749
750
def scaling_xyz(self):
    """The scaling factors for each of the three dimensions. XYZ order (for MONAI)."""
    return self.anisotropy_zoom_factor(self.resolution_xyz())

scaling_zyx

scaling_zyx()

The scaling factors for each of the three dimensions. ZYX order (for napari).

Source code in napari_cellseg3d/interface.py
757
758
759
def scaling_zyx(self):
    """The scaling factors for each of the three dimensions. ZYX order (for napari)."""
    return self.anisotropy_zoom_factor(self.resolution_zyx())

Button

Bases: QPushButton

Class for a button with a title and connected to a function when clicked. Inherits from QPushButton.

Parameters:

Name Type Description Default
title str - like

title of the button. Defaults to None, if None no title is set

None
func callable

function to execute when button is clicked. Defaults to None, no binding is made if None

None
parent QWidget

parent QWidget to add button to. Defaults to None, no parent is set if None

None
fixed bool

if True, will set the size policy of the button to Fixed in h and w. Defaults to True.

True

Methods:

Name Description
__init__

Creates a button with a title and a function to execute when clicked.

visibility_condition

Provide a QCheckBox to use to determine whether to show the button or not.

Source code in napari_cellseg3d/interface.py
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
class Button(QPushButton):
    """Class for a button with a title and connected to a function when clicked. Inherits from QPushButton.

    Args:
        title (str-like): title of the button. Defaults to None, if None no title is set
        func (callable): function to execute when button is clicked. Defaults to None, no binding is made if None
        parent (QWidget): parent QWidget to add button to. Defaults to None, no parent is set if None
        fixed (bool): if True, will set the size policy of the button to Fixed in h and w. Defaults to True.

    """

    def __init__(
        self,
        title: str = None,
        func: callable = None,
        parent: Optional[QWidget] = None,
        fixed: Optional[bool] = True,
    ):
        """Creates a button with a title and a function to execute when clicked."""
        super().__init__(parent)
        if title is not None:
            self.setText(title)

        if func is not None:
            self.clicked.connect(func)

        if fixed:
            self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

    def visibility_condition(self, checkbox):
        """Provide a QCheckBox to use to determine whether to show the button or not."""
        toggle_visibility(checkbox, self)

__init__

__init__(title: str = None, func: callable = None, parent: Optional[QWidget] = None, fixed: Optional[bool] = True)

Creates a button with a title and a function to execute when clicked.

Source code in napari_cellseg3d/interface.py
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def __init__(
    self,
    title: str = None,
    func: callable = None,
    parent: Optional[QWidget] = None,
    fixed: Optional[bool] = True,
):
    """Creates a button with a title and a function to execute when clicked."""
    super().__init__(parent)
    if title is not None:
        self.setText(title)

    if func is not None:
        self.clicked.connect(func)

    if fixed:
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

visibility_condition

visibility_condition(checkbox)

Provide a QCheckBox to use to determine whether to show the button or not.

Source code in napari_cellseg3d/interface.py
418
419
420
def visibility_condition(self, checkbox):
    """Provide a QCheckBox to use to determine whether to show the button or not."""
    toggle_visibility(checkbox, self)

CheckBox

Bases: QCheckBox

Shortcut class for creating QCheckBox with a title and a function.

Methods:

Name Description
__init__

Creates a checkbox with a title and a function to execute when toggled.

Source code in napari_cellseg3d/interface.py
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
class CheckBox(QCheckBox):
    """Shortcut class for creating QCheckBox with a title and a function."""

    def __init__(
        self,
        title: Optional[str] = None,
        func: Optional[callable] = None,
        parent: Optional[QWidget] = None,
        fixed: Optional[bool] = True,
    ):
        """Creates a checkbox with a title and a function to execute when toggled.

        Args:
            title (str-like): title of the checkbox. Defaults to None, if None no title is set
            func (callable): function to execute when checkbox is toggled. Defaults to None, no binding is made if None
            parent (QWidget): parent QWidget to add checkbox to. Defaults to None, no parent is set if None
            fixed (bool): if True, will set the size policy of the checkbox to Fixed in h and w. Defaults to True.
        """
        super().__init__(title, parent)
        if fixed:
            self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        if func is not None:
            self.toggled.connect(func)

__init__

__init__(title: Optional[str] = None, func: Optional[callable] = None, parent: Optional[QWidget] = None, fixed: Optional[bool] = True)

Creates a checkbox with a title and a function to execute when toggled.

Parameters:

Name Type Description Default
title str - like

title of the checkbox. Defaults to None, if None no title is set

None
func callable

function to execute when checkbox is toggled. Defaults to None, no binding is made if None

None
parent QWidget

parent QWidget to add checkbox to. Defaults to None, no parent is set if None

None
fixed bool

if True, will set the size policy of the checkbox to Fixed in h and w. Defaults to True.

True
Source code in napari_cellseg3d/interface.py
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
def __init__(
    self,
    title: Optional[str] = None,
    func: Optional[callable] = None,
    parent: Optional[QWidget] = None,
    fixed: Optional[bool] = True,
):
    """Creates a checkbox with a title and a function to execute when toggled.

    Args:
        title (str-like): title of the checkbox. Defaults to None, if None no title is set
        func (callable): function to execute when checkbox is toggled. Defaults to None, no binding is made if None
        parent (QWidget): parent QWidget to add checkbox to. Defaults to None, no parent is set if None
        fixed (bool): if True, will set the size policy of the checkbox to Fixed in h and w. Defaults to True.
    """
    super().__init__(title, parent)
    if fixed:
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
    if func is not None:
        self.toggled.connect(func)

ContainerWidget

Bases: QWidget

Class for a container widget that can contain other widgets.

Methods:

Name Description
__init__

Creates a container widget that can contain other widgets.

Source code in napari_cellseg3d/interface.py
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
class ContainerWidget(QWidget):
    """Class for a container widget that can contain other widgets."""

    def __init__(self, l=0, t=0, r=1, b=11, vertical=True, parent=None, fixed=True):
        """Creates a container widget that can contain other widgets.

        Args:
            l: left margin in pixels
            t: top margin in pixels
            r: right margin in pixels
            b: bottom margin in pixels
            vertical: if True, renders vertically. Horizontal otherwise
            parent: parent QWidget
            fixed: uses QLayout.SetFixedSize if True
        """
        super().__init__(parent)
        self.layout = None

        if vertical:
            self.layout = QVBoxLayout(self)
        else:
            self.layout = QHBoxLayout(self)

        self.layout.setContentsMargins(l, t, r, b)
        if fixed:
            self.layout.setSizeConstraint(QLayout.SetFixedSize)

__init__

__init__(l=0, t=0, r=1, b=11, vertical=True, parent=None, fixed=True)

Creates a container widget that can contain other widgets.

Parameters:

Name Type Description Default
l

left margin in pixels

0
t

top margin in pixels

0
r

right margin in pixels

1
b

bottom margin in pixels

11
vertical

if True, renders vertically. Horizontal otherwise

True
parent

parent QWidget

None
fixed

uses QLayout.SetFixedSize if True

True
Source code in napari_cellseg3d/interface.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
def __init__(self, l=0, t=0, r=1, b=11, vertical=True, parent=None, fixed=True):
    """Creates a container widget that can contain other widgets.

    Args:
        l: left margin in pixels
        t: top margin in pixels
        r: right margin in pixels
        b: bottom margin in pixels
        vertical: if True, renders vertically. Horizontal otherwise
        parent: parent QWidget
        fixed: uses QLayout.SetFixedSize if True
    """
    super().__init__(parent)
    self.layout = None

    if vertical:
        self.layout = QVBoxLayout(self)
    else:
        self.layout = QHBoxLayout(self)

    self.layout.setContentsMargins(l, t, r, b)
    if fixed:
        self.layout.setSizeConstraint(QLayout.SetFixedSize)

DoubleIncrementCounter

Bases: QDoubleSpinBox

Class implementing a number counter with increments (spin box) for floats.

Methods:

Name Description
__init__

Creates a DoubleIncrementCounter.

make_n

Creates n increment counters with the specified parameters.

set_visibility

Sets the visibility of the counter and its label.

Attributes:

Name Type Description
precision

Get current precision of the box.

tooltips

Gets the tooltip of both the DoubleIncrementCounter and its label.

Source code in napari_cellseg3d/interface.py
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
class DoubleIncrementCounter(QDoubleSpinBox):
    """Class implementing a number counter with increments (spin box) for floats."""

    def __init__(
        self,
        lower: Optional[float] = 0.0,
        upper: Optional[float] = 1000.0,
        default: Optional[float] = 0.0,
        step: Optional[float] = 1.0,
        parent: Optional[QWidget] = None,
        fixed: Optional[bool] = True,
        text_label: Optional[str] = None,
    ):
        """Creates a DoubleIncrementCounter.

        Args:
            lower (Optional[float]): minimum value, defaults to 0
            upper (Optional[float]): maximum value, defaults to 10
            default (Optional[float]): default value, defaults to 0
            step (Optional[float]): step value, defaults to 1
            parent: parent widget, defaults to None
            fixed (bool): if True, sets the QSizePolicy of the spinbox to Fixed
            text_label (Optional[str]): if provided, creates a label with the chosen title to use with the counter
        """
        super().__init__(parent)
        set_spinbox(self, lower, upper, default, step, fixed)

        self.layout = None

        if text_label is not None:
            self.label = make_label(name=text_label)
        # self.valueChanged.connect(self._update_step)
        self.setStepType(QAbstractSpinBox.StepType.AdaptiveDecimalStepType)

    # def _update_step(self):
    #     if self.value() <= 1:
    #         self.setSingleStep(0.1)
    #     else:
    #         self.setSingleStep(1)

    @property
    def tooltips(self):
        """Gets the tooltip of both the DoubleIncrementCounter and its label."""
        return self.toolTip()

    @tooltips.setter
    def tooltips(self, tooltip: str):
        """Sets the tooltip of both the DoubleIncrementCounter and its label."""
        self.setToolTip(tooltip)
        if self.label is not None:
            self.label.setToolTip(tooltip)

    @property
    def precision(self):
        """Get current precision of the box."""
        return self.decimals()

    @precision.setter
    def precision(self, decimals: int):
        """Sets the precision of the box to the specified number of decimals."""
        self.setDecimals(decimals)

    @classmethod
    def make_n(
        cls,
        n: int = 2,
        lower: float = 0,
        upper: float = 10,
        default: float = 0,
        step: float = 1,
        parent: Optional[QWidget] = None,
        fixed: Optional[bool] = True,
    ):
        """Creates n increment counters with the specified parameters."""
        return make_n_spinboxes(cls, n, lower, upper, default, step, parent, fixed)

    def set_visibility(self, visible: bool):
        """Sets the visibility of the counter and its label."""
        self.setVisible(visible)
        self.label.setVisible(visible)

precision property writable

precision

Get current precision of the box.

tooltips property writable

tooltips

Gets the tooltip of both the DoubleIncrementCounter and its label.

__init__

__init__(lower: Optional[float] = 0.0, upper: Optional[float] = 1000.0, default: Optional[float] = 0.0, step: Optional[float] = 1.0, parent: Optional[QWidget] = None, fixed: Optional[bool] = True, text_label: Optional[str] = None)

Creates a DoubleIncrementCounter.

Parameters:

Name Type Description Default
lower Optional[float]

minimum value, defaults to 0

0.0
upper Optional[float]

maximum value, defaults to 10

1000.0
default Optional[float]

default value, defaults to 0

0.0
step Optional[float]

step value, defaults to 1

1.0
parent Optional[QWidget]

parent widget, defaults to None

None
fixed bool

if True, sets the QSizePolicy of the spinbox to Fixed

True
text_label Optional[str]

if provided, creates a label with the chosen title to use with the counter

None
Source code in napari_cellseg3d/interface.py
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
def __init__(
    self,
    lower: Optional[float] = 0.0,
    upper: Optional[float] = 1000.0,
    default: Optional[float] = 0.0,
    step: Optional[float] = 1.0,
    parent: Optional[QWidget] = None,
    fixed: Optional[bool] = True,
    text_label: Optional[str] = None,
):
    """Creates a DoubleIncrementCounter.

    Args:
        lower (Optional[float]): minimum value, defaults to 0
        upper (Optional[float]): maximum value, defaults to 10
        default (Optional[float]): default value, defaults to 0
        step (Optional[float]): step value, defaults to 1
        parent: parent widget, defaults to None
        fixed (bool): if True, sets the QSizePolicy of the spinbox to Fixed
        text_label (Optional[str]): if provided, creates a label with the chosen title to use with the counter
    """
    super().__init__(parent)
    set_spinbox(self, lower, upper, default, step, fixed)

    self.layout = None

    if text_label is not None:
        self.label = make_label(name=text_label)
    # self.valueChanged.connect(self._update_step)
    self.setStepType(QAbstractSpinBox.StepType.AdaptiveDecimalStepType)

make_n classmethod

make_n(n: int = 2, lower: float = 0, upper: float = 10, default: float = 0, step: float = 1, parent: Optional[QWidget] = None, fixed: Optional[bool] = True)

Creates n increment counters with the specified parameters.

Source code in napari_cellseg3d/interface.py
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
@classmethod
def make_n(
    cls,
    n: int = 2,
    lower: float = 0,
    upper: float = 10,
    default: float = 0,
    step: float = 1,
    parent: Optional[QWidget] = None,
    fixed: Optional[bool] = True,
):
    """Creates n increment counters with the specified parameters."""
    return make_n_spinboxes(cls, n, lower, upper, default, step, parent, fixed)

set_visibility

set_visibility(visible: bool)

Sets the visibility of the counter and its label.

Source code in napari_cellseg3d/interface.py
1258
1259
1260
1261
def set_visibility(self, visible: bool):
    """Sets the visibility of the counter and its label."""
    self.setVisible(visible)
    self.label.setVisible(visible)

DropdownMenu

Bases: QComboBox

Creates a dropdown menu with a title and adds specified entries to it.

Methods:

Name Description
__init__

Creates a dropdown menu with a title and adds specified entries to it.

get_items

Returns the items in the dropdown menu.

Source code in napari_cellseg3d/interface.py
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
class DropdownMenu(QComboBox):
    """Creates a dropdown menu with a title and adds specified entries to it."""

    def __init__(
        self,
        entries: Optional[list] = None,
        parent: Optional[QWidget] = None,
        text_label: Optional[str] = None,
        fixed: Optional[bool] = True,
    ):
        """Creates a dropdown menu with a title and adds specified entries to it.

        Args:
            entries (array(str)): Entries to add to the dropdown menu. Defaults to None, no entries if None
            parent (QWidget): parent QWidget to add dropdown menu to. Defaults to None, no parent is set if None
            text_label (str) : if not None, creates a QLabel with the contents of 'label', and returns the label as well
            fixed (bool): if True, will set the size policy of the dropdown menu to Fixed in h and w. Defaults to True.
        """
        super().__init__(parent)
        self.label = None
        if entries is not None:
            self.addItems(entries)
        if text_label is not None:
            self.label = QLabel(text_label)
        if fixed:
            self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

    def get_items(self):
        """Returns the items in the dropdown menu."""
        return [self.itemText(i) for i in range(self.count())]

__init__

__init__(entries: Optional[list] = None, parent: Optional[QWidget] = None, text_label: Optional[str] = None, fixed: Optional[bool] = True)

Creates a dropdown menu with a title and adds specified entries to it.

Parameters:

Name Type Description Default
entries array(str)

Entries to add to the dropdown menu. Defaults to None, no entries if None

None
parent QWidget

parent QWidget to add dropdown menu to. Defaults to None, no parent is set if None

None
text_label (str)

if not None, creates a QLabel with the contents of 'label', and returns the label as well

required
fixed bool

if True, will set the size policy of the dropdown menu to Fixed in h and w. Defaults to True.

True
Source code in napari_cellseg3d/interface.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
def __init__(
    self,
    entries: Optional[list] = None,
    parent: Optional[QWidget] = None,
    text_label: Optional[str] = None,
    fixed: Optional[bool] = True,
):
    """Creates a dropdown menu with a title and adds specified entries to it.

    Args:
        entries (array(str)): Entries to add to the dropdown menu. Defaults to None, no entries if None
        parent (QWidget): parent QWidget to add dropdown menu to. Defaults to None, no parent is set if None
        text_label (str) : if not None, creates a QLabel with the contents of 'label', and returns the label as well
        fixed (bool): if True, will set the size policy of the dropdown menu to Fixed in h and w. Defaults to True.
    """
    super().__init__(parent)
    self.label = None
    if entries is not None:
        self.addItems(entries)
    if text_label is not None:
        self.label = QLabel(text_label)
    if fixed:
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

get_items

get_items()

Returns the items in the dropdown menu.

Source code in napari_cellseg3d/interface.py
450
451
452
def get_items(self):
    """Returns the items in the dropdown menu."""
    return [self.itemText(i) for i in range(self.count())]

FilePathWidget

Bases: QWidget

Widget to handle the choice of file paths for data throughout the plugin.

Provides the following elements

An "Open" button to show a file dialog (defined externally) A QLineEdit in read only to display the chosen path/file

Methods:

Name Description
__init__

Creates a FilePathWidget.

build

Builds the layout of the widget.

check_ready

Check if a path is correctly set.

update_field_color

Updates the background of the text field.

Attributes:

Name Type Description
button

Get "Open" button.

required

Get whether the field is required or not.

text_field

Get text field with file path.

tooltips

Get the tooltip of the text field and button.

Source code in napari_cellseg3d/interface.py
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
class FilePathWidget(QWidget):  # TODO include load as folder
    """Widget to handle the choice of file paths for data throughout the plugin.

    Provides the following elements :
        An "Open" button to show a file dialog (defined externally)
        A QLineEdit in read only to display the chosen path/file
    """

    def __init__(
        self,
        description: str,
        file_function: callable,
        parent: Optional[QWidget] = None,
        required: Optional[bool] = True,
        default: Optional[str] = None,
    ):
        """Creates a FilePathWidget.

        Args:
            description (str): Initial text to add to the text box
            file_function (callable): Function to handle the file dialog
            parent (Optional[QWidget]): parent QWidget
            required (Optional[bool]): if True, field will be highlighted in red if empty. Defaults to False.
            default (Optional[str]): default path to use. Defaults to None.
        """
        super().__init__(parent)
        self._layout = QHBoxLayout()
        self._layout.setSpacing(0)
        self._layout.setContentsMargins(0, 0, 0, 0)

        self._initial_desc = description
        self._text_field = QLineEdit(description, self)

        self._button = Button("Open", file_function, parent=self, fixed=True)

        self._text_field.setReadOnly(True)  # for user only
        if default is not None:
            self._text_field.setText(default)

        self._required = required

        self.build()
        self.check_ready()
        self.text_field.textChanged.connect(self.check_ready)

    def build(self):
        """Builds the layout of the widget."""
        add_widgets(
            self._layout,
            [combine_blocks(self.button, self.text_field, min_spacing=5, b=0)],
            ABS_AL,
        )
        self.setLayout(self._layout)

    @property
    def tooltips(self):
        """Get the tooltip of the text field and button."""
        return self._text_field.toolTip()

    @tooltips.setter
    def tooltips(self, tooltip: str):
        """Set the tooltip of the text field and button."""
        self._text_field.setToolTip(tooltip)
        self._button.setToolTip(tooltip)

    @property
    def text_field(self):
        """Get text field with file path."""
        return self._text_field

    @text_field.setter
    def text_field(self, text: str):
        """Sets the initial description in the text field, makes it the new default path."""
        self._initial_desc = text
        self.tooltips = text
        self._text_field.setText(text)

    @property
    def button(self):
        """Get "Open" button."""
        return self._button

    def check_ready(self):
        """Check if a path is correctly set."""
        if self.text_field.text() in ["", self._initial_desc] and self.required:
            self.update_field_color("indianred")
            self.text_field.setToolTip("Mandatory field !")
            return False
        self.update_field_color(f"{napari_param_darkgrey}")
        self.text_field.setToolTip(f"{self.text_field.text()}")
        return True

    @property
    def required(self):
        """Get whether the field is required or not."""
        return self._required

    @required.setter
    def required(self, is_required):
        """If set to True, will be colored red if incorrectly set."""
        self.check_ready()
        self._required = is_required

    def update_field_color(self, color: str):
        """Updates the background of the text field."""
        self.text_field.setStyleSheet(f"background-color : {color}")
        self.text_field.style().unpolish(self.text_field)
        self.text_field.style().polish(self.text_field)

button property

button

Get "Open" button.

required property writable

required

Get whether the field is required or not.

text_field property writable

text_field

Get text field with file path.

tooltips property writable

tooltips

Get the tooltip of the text field and button.

__init__

__init__(description: str, file_function: callable, parent: Optional[QWidget] = None, required: Optional[bool] = True, default: Optional[str] = None)

Creates a FilePathWidget.

Parameters:

Name Type Description Default
description str

Initial text to add to the text box

required
file_function callable

Function to handle the file dialog

required
parent Optional[QWidget]

parent QWidget

None
required Optional[bool]

if True, field will be highlighted in red if empty. Defaults to False.

True
default Optional[str]

default path to use. Defaults to None.

None
Source code in napari_cellseg3d/interface.py
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
def __init__(
    self,
    description: str,
    file_function: callable,
    parent: Optional[QWidget] = None,
    required: Optional[bool] = True,
    default: Optional[str] = None,
):
    """Creates a FilePathWidget.

    Args:
        description (str): Initial text to add to the text box
        file_function (callable): Function to handle the file dialog
        parent (Optional[QWidget]): parent QWidget
        required (Optional[bool]): if True, field will be highlighted in red if empty. Defaults to False.
        default (Optional[str]): default path to use. Defaults to None.
    """
    super().__init__(parent)
    self._layout = QHBoxLayout()
    self._layout.setSpacing(0)
    self._layout.setContentsMargins(0, 0, 0, 0)

    self._initial_desc = description
    self._text_field = QLineEdit(description, self)

    self._button = Button("Open", file_function, parent=self, fixed=True)

    self._text_field.setReadOnly(True)  # for user only
    if default is not None:
        self._text_field.setText(default)

    self._required = required

    self.build()
    self.check_ready()
    self.text_field.textChanged.connect(self.check_ready)

build

build()

Builds the layout of the widget.

Source code in napari_cellseg3d/interface.py
991
992
993
994
995
996
997
998
def build(self):
    """Builds the layout of the widget."""
    add_widgets(
        self._layout,
        [combine_blocks(self.button, self.text_field, min_spacing=5, b=0)],
        ABS_AL,
    )
    self.setLayout(self._layout)

check_ready

check_ready()

Check if a path is correctly set.

Source code in napari_cellseg3d/interface.py
1028
1029
1030
1031
1032
1033
1034
1035
1036
def check_ready(self):
    """Check if a path is correctly set."""
    if self.text_field.text() in ["", self._initial_desc] and self.required:
        self.update_field_color("indianred")
        self.text_field.setToolTip("Mandatory field !")
        return False
    self.update_field_color(f"{napari_param_darkgrey}")
    self.text_field.setToolTip(f"{self.text_field.text()}")
    return True

update_field_color

update_field_color(color: str)

Updates the background of the text field.

Source code in napari_cellseg3d/interface.py
1049
1050
1051
1052
1053
def update_field_color(self, color: str):
    """Updates the background of the text field."""
    self.text_field.setStyleSheet(f"background-color : {color}")
    self.text_field.style().unpolish(self.text_field)
    self.text_field.style().polish(self.text_field)

GroupedWidget

Bases: QGroupBox

Subclass of QGroupBox designed to easily group widgets belonging to a same category.

Methods:

Name Description
__init__

Creates a GroupedWidget.

create_single_widget_group

Creates a group with a single widget in it.

Source code in napari_cellseg3d/interface.py
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
class GroupedWidget(QGroupBox):
    """Subclass of QGroupBox designed to easily group widgets belonging to a same category."""

    def __init__(self, title, l=7, t=20, r=7, b=11, parent=None):
        """Creates a GroupedWidget."""
        super().__init__(title, parent)

        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        self.layout = QVBoxLayout()
        self.layout.setContentsMargins(l, t, r, b)
        self.layout.setSizeConstraint(QLayout.SetFixedSize)

    def _set_layout(self):
        """Sets the layout of the widget."""
        self.setLayout(self.layout)

    @classmethod
    def create_single_widget_group(
        cls,
        title,
        widget,
        layout,
        l=7,
        t=20,
        r=7,
        b=11,
        alignment=LEFT_AL,
    ):
        """Creates a group with a single widget in it."""
        group = cls(title, l, t, r, b)
        group.layout.addWidget(widget, alignment=alignment)
        group.setLayout(group.layout)
        layout.addWidget(group, alignment=alignment)
        return group

__init__

__init__(title, l=7, t=20, r=7, b=11, parent=None)

Creates a GroupedWidget.

Source code in napari_cellseg3d/interface.py
1430
1431
1432
1433
1434
1435
1436
1437
1438
def __init__(self, title, l=7, t=20, r=7, b=11, parent=None):
    """Creates a GroupedWidget."""
    super().__init__(title, parent)

    self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

    self.layout = QVBoxLayout()
    self.layout.setContentsMargins(l, t, r, b)
    self.layout.setSizeConstraint(QLayout.SetFixedSize)

create_single_widget_group classmethod

create_single_widget_group(title, widget, layout, l=7, t=20, r=7, b=11, alignment=LEFT_AL)

Creates a group with a single widget in it.

Source code in napari_cellseg3d/interface.py
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
@classmethod
def create_single_widget_group(
    cls,
    title,
    widget,
    layout,
    l=7,
    t=20,
    r=7,
    b=11,
    alignment=LEFT_AL,
):
    """Creates a group with a single widget in it."""
    group = cls(title, l, t, r, b)
    group.layout.addWidget(widget, alignment=alignment)
    group.setLayout(group.layout)
    layout.addWidget(group, alignment=alignment)
    return group

IntIncrementCounter

Bases: QSpinBox

Class implementing a number counter with increments (spin box) for int.

Methods:

Name Description
__init__

Creates an IntIncrementCounter.

make_n

Creates n increment counters with the specified parameters.

Attributes:

Name Type Description
tooltips

Gets the tooltip of both the IntIncrementCounter and its label.

Source code in napari_cellseg3d/interface.py
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
class IntIncrementCounter(QSpinBox):
    """Class implementing a number counter with increments (spin box) for int."""

    def __init__(
        self,
        lower=0,
        upper=10,
        default=0,
        step=1,
        parent: Optional[QWidget] = None,
        fixed: Optional[bool] = True,
        text_label: Optional[str] = None,
    ):
        """Creates an IntIncrementCounter.

        Args:
            lower (Optional[int]): minimum value, defaults to 0
            upper (Optional[int]): maximum value, defaults to 10
            default (Optional[int]): default value, defaults to 0
            step (Optional[int]): step value, defaults to 1
            parent: parent widget, defaults to None
            fixed (bool): if True, sets the QSizePolicy of the spinbox to Fixed
            text_label (Optional[str]): if provided, creates a label with the chosen title to use with the counter
        """
        super().__init__(parent)
        set_spinbox(self, lower, upper, default, step, fixed)

        self.label = None
        # self.container = None

        if text_label is not None:
            self.label = make_label(name=text_label)

    @property
    def tooltips(self):
        """Gets the tooltip of both the IntIncrementCounter and its label."""
        return self.toolTip()

    @tooltips.setter
    def tooltips(self, tooltip):
        """Sets the tooltip of both the IntIncrementCounter and its label."""
        self.setToolTip(tooltip)
        self.label.setToolTip(tooltip)

    @classmethod
    def make_n(
        cls,
        n: int = 2,
        lower: int = 0,
        upper: int = 10,
        default: int = 0,
        step: int = 1,
        parent: Optional[QWidget] = None,
        fixed: Optional[bool] = True,
    ):
        """Creates n increment counters with the specified parameters."""
        return make_n_spinboxes(cls, n, lower, upper, default, step, parent, fixed)

tooltips property writable

tooltips

Gets the tooltip of both the IntIncrementCounter and its label.

__init__

__init__(lower=0, upper=10, default=0, step=1, parent: Optional[QWidget] = None, fixed: Optional[bool] = True, text_label: Optional[str] = None)

Creates an IntIncrementCounter.

Parameters:

Name Type Description Default
lower Optional[int]

minimum value, defaults to 0

0
upper Optional[int]

maximum value, defaults to 10

10
default Optional[int]

default value, defaults to 0

0
step Optional[int]

step value, defaults to 1

1
parent Optional[QWidget]

parent widget, defaults to None

None
fixed bool

if True, sets the QSizePolicy of the spinbox to Fixed

True
text_label Optional[str]

if provided, creates a label with the chosen title to use with the counter

None
Source code in napari_cellseg3d/interface.py
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
def __init__(
    self,
    lower=0,
    upper=10,
    default=0,
    step=1,
    parent: Optional[QWidget] = None,
    fixed: Optional[bool] = True,
    text_label: Optional[str] = None,
):
    """Creates an IntIncrementCounter.

    Args:
        lower (Optional[int]): minimum value, defaults to 0
        upper (Optional[int]): maximum value, defaults to 10
        default (Optional[int]): default value, defaults to 0
        step (Optional[int]): step value, defaults to 1
        parent: parent widget, defaults to None
        fixed (bool): if True, sets the QSizePolicy of the spinbox to Fixed
        text_label (Optional[str]): if provided, creates a label with the chosen title to use with the counter
    """
    super().__init__(parent)
    set_spinbox(self, lower, upper, default, step, fixed)

    self.label = None
    # self.container = None

    if text_label is not None:
        self.label = make_label(name=text_label)

make_n classmethod

make_n(n: int = 2, lower: int = 0, upper: int = 10, default: int = 0, step: int = 1, parent: Optional[QWidget] = None, fixed: Optional[bool] = True)

Creates n increment counters with the specified parameters.

Source code in napari_cellseg3d/interface.py
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
@classmethod
def make_n(
    cls,
    n: int = 2,
    lower: int = 0,
    upper: int = 10,
    default: int = 0,
    step: int = 1,
    parent: Optional[QWidget] = None,
    fixed: Optional[bool] = True,
):
    """Creates n increment counters with the specified parameters."""
    return make_n_spinboxes(cls, n, lower, upper, default, step, parent, fixed)

LayerSelecter

Bases: ContainerWidget

Class that creates a dropdown menu to select a layer from a napari viewer.

Methods:

Name Description
__init__

Creates an instance of LayerSelecter.

layer

Returns the layer selected in the dropdown menu.

layer_data

Returns the data of the layer selected in the dropdown menu.

layer_name

Returns the name of the layer selected in the dropdown menu.

set_layer_type

Sets the layer type to be selected in the dropdown menu.

Source code in napari_cellseg3d/interface.py
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
class LayerSelecter(ContainerWidget):
    """Class that creates a dropdown menu to select a layer from a napari viewer."""

    def __init__(
        self, viewer, name="Layer", layer_type=napari.layers.Layer, parent=None
    ):
        """Creates an instance of LayerSelecter."""
        super().__init__(parent=parent, fixed=False)
        self._viewer = viewer
        self.layer_type = layer_type

        self.layer_list = DropdownMenu(parent=self, text_label=name, fixed=False)
        self.layer_description = make_label("Shape:", parent=self)
        self.layer_description.setVisible(False)
        # self.layer_list.setSizeAdjustPolicy(QComboBox.AdjustToContents) # use tooltip instead ?

        # connect to LayerList events
        self._viewer.layers.events.inserted.connect(partial(self._add_layer))
        self._viewer.layers.events.removed.connect(partial(self._remove_layer))
        self._viewer.layers.events.changed.connect(self._check_for_layers)

        # update self.layer_list when layers are added or removed
        self.layer_list.currentIndexChanged.connect(self._update_tooltip)
        self.layer_list.currentTextChanged.connect(self._update_description)

        add_widgets(
            self.layout,
            [self.layer_list.label, self.layer_list, self.layer_description],
        )
        self._check_for_layers()

    def _get_all_layers(self):
        return [self.layer_list.itemText(i) for i in range(self.layer_list.count())]

    def _check_for_layers(self):
        """Check for layers of the correct type and update the dropdown menu.

        Also removes layers that have been removed from the viewer.
        """
        for layer in self._viewer.layers:
            layer.events.name.connect(self._rename_layer)

            if (
                isinstance(layer, self.layer_type)
                and layer.name not in self._get_all_layers()
            ):
                logger.debug(f"Layer {layer.name} - List : {self._get_all_layers()}")
                # add new layers of correct type
                self.layer_list.addItem(layer.name)
                logger.debug(f"Layer {layer.name} has been added to the menu")
                # break
                # once added, check again for previously renamed layers
                self._check_for_removed_layer(layer)

            if layer.name in self._get_all_layers() and not isinstance(
                layer, self.layer_type
            ):
                # remove layers of incorrect type
                index = self.layer_list.findText(layer.name)
                self.layer_list.removeItem(index)
                logger.debug(f"Layer {layer.name} has been removed from the menu")

        self._check_for_removed_layers()
        self._update_tooltip()
        self._update_description()

    def _check_for_removed_layer(self, layer):
        """Check if a specific layer has been removed from the viewer and must be removed from the menu."""
        if isinstance(layer, str):
            name = layer
        elif isinstance(layer, self.layer_type):
            name = layer.name
        else:
            logger.warning("Layer is not a string or a valid napari layer")
            return

        if name in self._get_all_layers() and name not in [
            l.name for l in self._viewer.layers
        ]:
            index = self.layer_list.findText(name)
            self.layer_list.removeItem(index)
            logger.debug(f"Layer {name} has been removed from the menu")

    def _check_for_removed_layers(self):
        """Check for layers that have been removed from the viewer and must be removed from the menu."""
        for layer in self._get_all_layers():
            self._check_for_removed_layer(layer)

    def _update_tooltip(self):
        self.layer_list.setToolTip(self.layer_list.currentText())

    def _update_description(self):
        try:
            if self.layer_list.currentText() != "":
                try:
                    shape_desc = f"Shape : {self.layer_data().shape}"
                    self.layer_description.setText(shape_desc)
                    self.layer_description.setVisible(True)
                except AttributeError:
                    self.layer_description.setVisible(False)
            else:
                self.layer_description.setVisible(False)
        except KeyError:
            self.layer_description.setVisible(False)

    def _add_layer(self, event):
        inserted_layer = event.value

        if isinstance(inserted_layer, self.layer_type):
            self.layer_list.addItem(inserted_layer.name)

        # check for renaming
        inserted_layer.events.name.connect(self._rename_layer)

    def _rename_layer(self, _):
        # on layer rename, check for removed/new layers
        self._check_for_layers()

    def _remove_layer(self, event):
        removed_layer = event.value

        if isinstance(removed_layer, self.layer_type) and removed_layer.name in [
            self.layer_list.itemText(i) for i in range(self.layer_list.count())
        ]:
            index = self.layer_list.findText(removed_layer.name)
            self.layer_list.removeItem(index)

    def set_layer_type(self, layer_type):  # no @property due to Qt constraint
        """Sets the layer type to be selected in the dropdown menu."""
        self.layer_type = layer_type
        [self.layer_list.removeItem(i) for i in range(self.layer_list.count())]
        self._check_for_layers()

    def layer(self):
        """Returns the layer selected in the dropdown menu."""
        try:
            return self._viewer.layers[self.layer_name()]
        except ValueError:
            return None

    def layer_name(self):
        """Returns the name of the layer selected in the dropdown menu."""
        try:
            return self.layer_list.currentText()
        except (KeyError, ValueError):
            logger.warning("Layer list is empty")
            return None

    def layer_data(self):
        """Returns the data of the layer selected in the dropdown menu."""
        if self.layer_list.count() < 1:
            logger.debug("Layer list is empty")
            return None
        try:
            return self.layer().data
        except (KeyError, ValueError):
            msg = f"Layer {self.layer_name()} has no data. Layer might have been renamed or removed."
            logger.warning(msg)
            warn(msg, stacklevel=1)
            return None

__init__

__init__(viewer, name='Layer', layer_type=napari.layers.Layer, parent=None)

Creates an instance of LayerSelecter.

Source code in napari_cellseg3d/interface.py
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
def __init__(
    self, viewer, name="Layer", layer_type=napari.layers.Layer, parent=None
):
    """Creates an instance of LayerSelecter."""
    super().__init__(parent=parent, fixed=False)
    self._viewer = viewer
    self.layer_type = layer_type

    self.layer_list = DropdownMenu(parent=self, text_label=name, fixed=False)
    self.layer_description = make_label("Shape:", parent=self)
    self.layer_description.setVisible(False)
    # self.layer_list.setSizeAdjustPolicy(QComboBox.AdjustToContents) # use tooltip instead ?

    # connect to LayerList events
    self._viewer.layers.events.inserted.connect(partial(self._add_layer))
    self._viewer.layers.events.removed.connect(partial(self._remove_layer))
    self._viewer.layers.events.changed.connect(self._check_for_layers)

    # update self.layer_list when layers are added or removed
    self.layer_list.currentIndexChanged.connect(self._update_tooltip)
    self.layer_list.currentTextChanged.connect(self._update_description)

    add_widgets(
        self.layout,
        [self.layer_list.label, self.layer_list, self.layer_description],
    )
    self._check_for_layers()

layer

layer()

Returns the layer selected in the dropdown menu.

Source code in napari_cellseg3d/interface.py
917
918
919
920
921
922
def layer(self):
    """Returns the layer selected in the dropdown menu."""
    try:
        return self._viewer.layers[self.layer_name()]
    except ValueError:
        return None

layer_data

layer_data()

Returns the data of the layer selected in the dropdown menu.

Source code in napari_cellseg3d/interface.py
932
933
934
935
936
937
938
939
940
941
942
943
def layer_data(self):
    """Returns the data of the layer selected in the dropdown menu."""
    if self.layer_list.count() < 1:
        logger.debug("Layer list is empty")
        return None
    try:
        return self.layer().data
    except (KeyError, ValueError):
        msg = f"Layer {self.layer_name()} has no data. Layer might have been renamed or removed."
        logger.warning(msg)
        warn(msg, stacklevel=1)
        return None

layer_name

layer_name()

Returns the name of the layer selected in the dropdown menu.

Source code in napari_cellseg3d/interface.py
924
925
926
927
928
929
930
def layer_name(self):
    """Returns the name of the layer selected in the dropdown menu."""
    try:
        return self.layer_list.currentText()
    except (KeyError, ValueError):
        logger.warning("Layer list is empty")
        return None

set_layer_type

set_layer_type(layer_type)

Sets the layer type to be selected in the dropdown menu.

Source code in napari_cellseg3d/interface.py
911
912
913
914
915
def set_layer_type(self, layer_type):  # no @property due to Qt constraint
    """Sets the layer type to be selected in the dropdown menu."""
    self.layer_type = layer_type
    [self.layer_list.removeItem(i) for i in range(self.layer_list.count())]
    self._check_for_layers()

Log

Bases: QTextEdit

Class to implement a log for important user info. Should be thread-safe.

Methods:

Name Description
__init__

Creates a log with a lock for multithreading.

error

Show exception and message from another thread.

flush

Flush the log.

print_and_log

Utility used to both print to terminal and log text to a QTextEdit item in a thread-safe manner. Use only for important user info.

replace_last_line

Replace last line. For use in progress bar.

warn

Show logger.warning from another thread.

write

Write message to log in a thread-safe manner.

Source code in napari_cellseg3d/interface.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
class Log(QTextEdit):
    """Class to implement a log for important user info. Should be thread-safe."""

    def __init__(self, parent=None):
        """Creates a log with a lock for multithreading.

        Args:
            parent (QWidget): parent widget to add Log instance to.
        """
        super().__init__(parent)

        # from qtpy.QtCore import QMetaType
        # parent.qRegisterMetaType<QTextCursor>("QTextCursor")

        self.lock = threading.Lock()

    def flush(self):
        """Flush the log."""
        pass

    def write(self, message):
        """Write message to log in a thread-safe manner.

        Args:
            message: string to be printed
        """
        self.lock.acquire()
        try:
            if not hasattr(self, "flag"):
                self.flag = False
            message = message.replace("\r", "").rstrip()
            if message:
                method = "replace_last_line" if self.flag else "append"
                QtCore.QMetaObject.invokeMethod(
                    self,
                    method,
                    QtCore.Qt.QueuedConnection,
                    QtCore.Q_ARG(str, message),
                )
                self.flag = True
            else:
                self.flag = False

        finally:
            self.lock.release()

    @QtCore.Slot(str)
    def replace_last_line(self, text):
        """Replace last line. For use in progress bar.

        Args:
            text: string to be printed
        """
        self.lock.acquire()
        try:
            cursor = self.textCursor()
            cursor.movePosition(QTextCursor.End)
            cursor.select(QTextCursor.BlockUnderCursor)
            cursor.removeSelectedText()
            cursor.insertBlock()
            self.setTextCursor(cursor)
            self.insertPlainText(text)
        finally:
            self.lock.release()

    def print_and_log(self, text, printing=True):
        """Utility used to both print to terminal and log text to a QTextEdit item in a thread-safe manner. Use only for important user info.

        Args:
            text (str): Text to be printed and logged
            printing (bool): Whether to print the message as well or not using logger.info(). Defaults to True.

        """
        self.lock.acquire()
        try:
            if printing:
                logger.info(text)
            # causes issue if you clik on terminal (tied to CMD QuickEdit mode on Windows)
            self.moveCursor(QTextCursor.End)
            self.insertPlainText(f"\n{text}")
            self.verticalScrollBar().setValue(self.verticalScrollBar().maximum())
        finally:
            self.lock.release()

    def warn(self, warning):
        """Show logger.warning from another thread.

        Args:
            warning: warning to be printed
        """
        self.lock.acquire()
        try:
            logger.warning(warning)
        finally:
            self.lock.release()

    def error(self, error, msg=None):
        """Show exception and message from another thread.

        Args:
            error: error to be printed
            msg: message to be printed
        """
        self.lock.acquire()
        try:
            logger.error(error, exc_info=True)
            if msg is not None:
                self.print_and_log(f"{msg} : {error}", printing=False)
            else:
                self.print_and_log(
                    f"Exception caught in another thread : {error}",
                    printing=False,
                )
            raise error
        finally:
            self.lock.release()

__init__

__init__(parent=None)

Creates a log with a lock for multithreading.

Parameters:

Name Type Description Default
parent QWidget

parent widget to add Log instance to.

None
Source code in napari_cellseg3d/interface.py
209
210
211
212
213
214
215
216
217
218
219
220
def __init__(self, parent=None):
    """Creates a log with a lock for multithreading.

    Args:
        parent (QWidget): parent widget to add Log instance to.
    """
    super().__init__(parent)

    # from qtpy.QtCore import QMetaType
    # parent.qRegisterMetaType<QTextCursor>("QTextCursor")

    self.lock = threading.Lock()

error

error(error, msg=None)

Show exception and message from another thread.

Parameters:

Name Type Description Default
error

error to be printed

required
msg

message to be printed

None
Source code in napari_cellseg3d/interface.py
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
def error(self, error, msg=None):
    """Show exception and message from another thread.

    Args:
        error: error to be printed
        msg: message to be printed
    """
    self.lock.acquire()
    try:
        logger.error(error, exc_info=True)
        if msg is not None:
            self.print_and_log(f"{msg} : {error}", printing=False)
        else:
            self.print_and_log(
                f"Exception caught in another thread : {error}",
                printing=False,
            )
        raise error
    finally:
        self.lock.release()

flush

flush()

Flush the log.

Source code in napari_cellseg3d/interface.py
222
223
224
def flush(self):
    """Flush the log."""
    pass

print_and_log

print_and_log(text, printing=True)

Utility used to both print to terminal and log text to a QTextEdit item in a thread-safe manner. Use only for important user info.

Parameters:

Name Type Description Default
text str

Text to be printed and logged

required
printing bool

Whether to print the message as well or not using logger.info(). Defaults to True.

True
Source code in napari_cellseg3d/interface.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def print_and_log(self, text, printing=True):
    """Utility used to both print to terminal and log text to a QTextEdit item in a thread-safe manner. Use only for important user info.

    Args:
        text (str): Text to be printed and logged
        printing (bool): Whether to print the message as well or not using logger.info(). Defaults to True.

    """
    self.lock.acquire()
    try:
        if printing:
            logger.info(text)
        # causes issue if you clik on terminal (tied to CMD QuickEdit mode on Windows)
        self.moveCursor(QTextCursor.End)
        self.insertPlainText(f"\n{text}")
        self.verticalScrollBar().setValue(self.verticalScrollBar().maximum())
    finally:
        self.lock.release()

replace_last_line

replace_last_line(text)

Replace last line. For use in progress bar.

Parameters:

Name Type Description Default
text

string to be printed

required
Source code in napari_cellseg3d/interface.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
@QtCore.Slot(str)
def replace_last_line(self, text):
    """Replace last line. For use in progress bar.

    Args:
        text: string to be printed
    """
    self.lock.acquire()
    try:
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.End)
        cursor.select(QTextCursor.BlockUnderCursor)
        cursor.removeSelectedText()
        cursor.insertBlock()
        self.setTextCursor(cursor)
        self.insertPlainText(text)
    finally:
        self.lock.release()

warn

warn(warning)

Show logger.warning from another thread.

Parameters:

Name Type Description Default
warning

warning to be printed

required
Source code in napari_cellseg3d/interface.py
290
291
292
293
294
295
296
297
298
299
300
def warn(self, warning):
    """Show logger.warning from another thread.

    Args:
        warning: warning to be printed
    """
    self.lock.acquire()
    try:
        logger.warning(warning)
    finally:
        self.lock.release()

write

write(message)

Write message to log in a thread-safe manner.

Parameters:

Name Type Description Default
message

string to be printed

required
Source code in napari_cellseg3d/interface.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
def write(self, message):
    """Write message to log in a thread-safe manner.

    Args:
        message: string to be printed
    """
    self.lock.acquire()
    try:
        if not hasattr(self, "flag"):
            self.flag = False
        message = message.replace("\r", "").rstrip()
        if message:
            method = "replace_last_line" if self.flag else "append"
            QtCore.QMetaObject.invokeMethod(
                self,
                method,
                QtCore.Qt.QueuedConnection,
                QtCore.Q_ARG(str, message),
            )
            self.flag = True
        else:
            self.flag = False

    finally:
        self.lock.release()

QWidgetSingleton

Bases: type(QObject)

To be used as a metaclass when making a singleton QWidget, meaning only one instance exists at a time.

Avoids unnecessary memory overhead and keeps user parameters even when a widget is closed.

Methods:

Name Description
__call__

Ensure only one instance of a QWidget with QWidgetSingleton as a metaclass exists at a time.

Source code in napari_cellseg3d/interface.py
83
84
85
86
87
88
89
90
91
92
93
94
95
class QWidgetSingleton(type(QObject)):
    """To be used as a metaclass when making a singleton QWidget, meaning only one instance exists at a time.

    Avoids unnecessary memory overhead and keeps user parameters even when a widget is closed.
    """

    _instances = {}

    def __call__(cls, *args, **kwargs):
        """Ensure only one instance of a QWidget with QWidgetSingleton as a metaclass exists at a time."""
        if cls not in cls._instances:
            cls._instances[cls] = super(QWidgetSingleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

__call__

__call__(*args, **kwargs)

Ensure only one instance of a QWidget with QWidgetSingleton as a metaclass exists at a time.

Source code in napari_cellseg3d/interface.py
91
92
93
94
95
def __call__(cls, *args, **kwargs):
    """Ensure only one instance of a QWidget with QWidgetSingleton as a metaclass exists at a time."""
    if cls not in cls._instances:
        cls._instances[cls] = super(QWidgetSingleton, cls).__call__(*args, **kwargs)
    return cls._instances[cls]

RadioButton

Bases: QRadioButton

Class for a radio button with a title and connected to a function when clicked. Inherits from QRadioButton.

Methods:

Name Description
__init__

Creates a radio button with a title and a function to execute when toggled.

Source code in napari_cellseg3d/interface.py
381
382
383
384
385
386
class RadioButton(QRadioButton):
    """Class for a radio button with a title and connected to a function when clicked. Inherits from QRadioButton."""

    def __init__(self, text: str = None, parent=None):
        """Creates a radio button with a title and a function to execute when toggled."""
        super().__init__(text, parent)

__init__

__init__(text: str = None, parent=None)

Creates a radio button with a title and a function to execute when toggled.

Source code in napari_cellseg3d/interface.py
384
385
386
def __init__(self, text: str = None, parent=None):
    """Creates a radio button with a title and a function to execute when toggled."""
    super().__init__(text, parent)

ScrollArea

Bases: QScrollArea

Creates a QScrollArea and sets it up, then adds the contained_layout to it.

Methods:

Name Description
__init__

Initializes a QScrollArea and sets it up, then adds the contained_layout to it.

make_scrollable

Factory method to create a scroll area in a widget.

Source code in napari_cellseg3d/interface.py
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
class ScrollArea(QScrollArea):
    """Creates a QScrollArea and sets it up, then adds the contained_layout to it."""

    def __init__(
        self,
        contained_layout: QLayout,
        min_wh: Optional[List[int]] = None,
        max_wh: Optional[List[int]] = None,
        base_wh: Optional[List[int]] = None,
        parent: Optional[QWidget] = None,
    ):
        """Initializes a QScrollArea and sets it up, then adds the contained_layout to it.

        Args:
          contained_layout (QLayout): the layout of widgets to be made scrollable
          min_wh (Optional[List[int]]): array of two ints for respectively the minimum width and minimum height of the scrollable area. Defaults to None, lets Qt decide if None
          max_wh (Optional[List[int]]): array of two ints for respectively the maximum width and maximum height of the scrollable area. Defaults to None, lets Qt decide if None
          base_wh (Optional[List[int]]): array of two ints for respectively the initial width and initial height of the scrollable area. Defaults to None, lets Qt decide if None
          parent (Optional[QWidget]): array of two ints for respectively the initial width and initial height of the scrollable area. Defaults to None, lets Qt decide if None
        """
        super().__init__(parent)

        self._container_widget = QWidget()  # required to use QScrollArea.setWidget()
        self._container_widget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Maximum)
        self._container_widget.setLayout(contained_layout)
        self._container_widget.adjustSize()

        self.setWidget(self._container_widget)
        self.setWidgetResizable(True)
        self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)

        if base_wh is not None:
            self.setBaseSize(base_wh[0], base_wh[1])
        if max_wh is not None:
            self.setMaximumSize(max_wh[0], max_wh[1])
        if min_wh is not None:
            self.setMinimumSize(min_wh[0], min_wh[1])

        self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOn)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)

    @classmethod
    def make_scrollable(
        cls,
        contained_layout: QLayout,
        parent: QWidget,
        min_wh: Optional[List[int]] = None,
        max_wh: Optional[List[int]] = None,
        base_wh: Optional[List[int]] = None,
    ):
        """Factory method to create a scroll area in a widget.

        Args:
            contained_layout (QLayout): the widget to be made scrollable
            parent (QWidget): the parent widget to add the resulting scroll area in
            min_wh (Optional[List[int]]): array of two ints for respectively the minimum width and minimum height of the scrollable area. Defaults to None, lets Qt decide if None
            max_wh (Optional[List[int]]): array of two ints for respectively the maximum width and maximum height of the scrollable area. Defaults to None, lets Qt decide if None
            base_wh (Optional[List[int]]): array of two ints for respectively the initial width and initial height of the scrollable area. Defaults to None, lets Qt decide if None
        """
        scroll = cls(contained_layout, min_wh, max_wh, base_wh)
        layout = QVBoxLayout(parent)
        # layout.setContentsMargins(0,0,1,1)
        layout.setSizeConstraint(QLayout.SetMinAndMaxSize)
        layout.addWidget(scroll)
        parent.setLayout(layout)

__init__

__init__(contained_layout: QLayout, min_wh: Optional[List[int]] = None, max_wh: Optional[List[int]] = None, base_wh: Optional[List[int]] = None, parent: Optional[QWidget] = None)

Initializes a QScrollArea and sets it up, then adds the contained_layout to it.

Parameters:

Name Type Description Default
contained_layout QLayout

the layout of widgets to be made scrollable

required
min_wh Optional[List[int]]

array of two ints for respectively the minimum width and minimum height of the scrollable area. Defaults to None, lets Qt decide if None

None
max_wh Optional[List[int]]

array of two ints for respectively the maximum width and maximum height of the scrollable area. Defaults to None, lets Qt decide if None

None
base_wh Optional[List[int]]

array of two ints for respectively the initial width and initial height of the scrollable area. Defaults to None, lets Qt decide if None

None
parent Optional[QWidget]

array of two ints for respectively the initial width and initial height of the scrollable area. Defaults to None, lets Qt decide if None

None
Source code in napari_cellseg3d/interface.py
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
def __init__(
    self,
    contained_layout: QLayout,
    min_wh: Optional[List[int]] = None,
    max_wh: Optional[List[int]] = None,
    base_wh: Optional[List[int]] = None,
    parent: Optional[QWidget] = None,
):
    """Initializes a QScrollArea and sets it up, then adds the contained_layout to it.

    Args:
      contained_layout (QLayout): the layout of widgets to be made scrollable
      min_wh (Optional[List[int]]): array of two ints for respectively the minimum width and minimum height of the scrollable area. Defaults to None, lets Qt decide if None
      max_wh (Optional[List[int]]): array of two ints for respectively the maximum width and maximum height of the scrollable area. Defaults to None, lets Qt decide if None
      base_wh (Optional[List[int]]): array of two ints for respectively the initial width and initial height of the scrollable area. Defaults to None, lets Qt decide if None
      parent (Optional[QWidget]): array of two ints for respectively the initial width and initial height of the scrollable area. Defaults to None, lets Qt decide if None
    """
    super().__init__(parent)

    self._container_widget = QWidget()  # required to use QScrollArea.setWidget()
    self._container_widget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Maximum)
    self._container_widget.setLayout(contained_layout)
    self._container_widget.adjustSize()

    self.setWidget(self._container_widget)
    self.setWidgetResizable(True)
    self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)

    if base_wh is not None:
        self.setBaseSize(base_wh[0], base_wh[1])
    if max_wh is not None:
        self.setMaximumSize(max_wh[0], max_wh[1])
    if min_wh is not None:
        self.setMinimumSize(min_wh[0], min_wh[1])

    self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOn)
    self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)

make_scrollable classmethod

make_scrollable(contained_layout: QLayout, parent: QWidget, min_wh: Optional[List[int]] = None, max_wh: Optional[List[int]] = None, base_wh: Optional[List[int]] = None)

Factory method to create a scroll area in a widget.

Parameters:

Name Type Description Default
contained_layout QLayout

the widget to be made scrollable

required
parent QWidget

the parent widget to add the resulting scroll area in

required
min_wh Optional[List[int]]

array of two ints for respectively the minimum width and minimum height of the scrollable area. Defaults to None, lets Qt decide if None

None
max_wh Optional[List[int]]

array of two ints for respectively the maximum width and maximum height of the scrollable area. Defaults to None, lets Qt decide if None

None
base_wh Optional[List[int]]

array of two ints for respectively the initial width and initial height of the scrollable area. Defaults to None, lets Qt decide if None

None
Source code in napari_cellseg3d/interface.py
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
@classmethod
def make_scrollable(
    cls,
    contained_layout: QLayout,
    parent: QWidget,
    min_wh: Optional[List[int]] = None,
    max_wh: Optional[List[int]] = None,
    base_wh: Optional[List[int]] = None,
):
    """Factory method to create a scroll area in a widget.

    Args:
        contained_layout (QLayout): the widget to be made scrollable
        parent (QWidget): the parent widget to add the resulting scroll area in
        min_wh (Optional[List[int]]): array of two ints for respectively the minimum width and minimum height of the scrollable area. Defaults to None, lets Qt decide if None
        max_wh (Optional[List[int]]): array of two ints for respectively the maximum width and maximum height of the scrollable area. Defaults to None, lets Qt decide if None
        base_wh (Optional[List[int]]): array of two ints for respectively the initial width and initial height of the scrollable area. Defaults to None, lets Qt decide if None
    """
    scroll = cls(contained_layout, min_wh, max_wh, base_wh)
    layout = QVBoxLayout(parent)
    # layout.setContentsMargins(0,0,1,1)
    layout.setSizeConstraint(QLayout.SetMinAndMaxSize)
    layout.addWidget(scroll)
    parent.setLayout(layout)

Slider

Bases: QSlider

Shortcut class to create a Slider widget.

Methods:

Name Description
__init__

Creates a slider to select a value between lower and upper, with a step.

set_visibility

Sets the visibility of the slider and its label.

Attributes:

Name Type Description
slider_value

Get value of the slider divided by self._divide_factor to implement floats in Slider.

tooltips

Get the tooltip of the slider.

value_text

Get value of the slide bar as string.

Source code in napari_cellseg3d/interface.py
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
class Slider(QSlider):
    """Shortcut class to create a Slider widget."""

    def __init__(
        self,
        lower: int = 0,
        upper: int = 100,
        step: int = 1,
        default: int = 0,
        divide_factor: float = 1.0,
        parent=None,
        orientation=Qt.Horizontal,
        text_label: str = None,
    ):
        """Creates a slider to select a value between lower and upper, with a step."""
        super().__init__(orientation, parent)

        if upper <= lower:
            raise ValueError("The minimum value cannot be below the maximum one")

        self.setMaximum(upper)
        self.setMinimum(lower)
        self.setSingleStep(step)

        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        self.label = None
        self.container = ContainerWidget(
            # parent=self.parent,
            b=0,
        )

        self._divide_factor = divide_factor
        self._value_label = QLineEdit(self.value_text, parent=self)

        if self._divide_factor == 1:
            self._value_label.setFixedWidth(20)
        elif self._divide_factor == 10:
            self._value_label.setFixedWidth(30)
        else:
            self._value_label.setFixedWidth(50)
        self._value_label.setAlignment(Qt.AlignCenter)
        self._value_label.setSizePolicy(
            QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed
        )

        self._value_label.setStyleSheet(
            f"background-color: {napari_param_grey};"
            f"border-radius: 5px;"
            "min - height: 12px;"
            "min - width: 12px;"
        )

        if text_label is not None:
            self.label = make_label(text_label, parent=self)

        if default < lower:
            self._warn_outside_bounds(default)
            default = lower
        elif default > upper:
            self._warn_outside_bounds(default)
            default = upper

        self.valueChanged.connect(self._update_value_label)
        self._value_label.textChanged.connect(self._update_slider)

        self.slider_value = default

        self._build_container()

    def set_visibility(self, visible: bool):
        """Sets the visibility of the slider and its label."""
        self.container.setVisible(visible)
        self.setVisible(visible)
        self.label.setVisible(visible)

    def _build_container(self):
        if self.label is not None:
            add_widgets(
                self.container.layout,
                [
                    self.label,
                    combine_blocks(self._value_label, self, b=0),
                ],
            )
        else:
            add_widgets(
                self.container.layout,
                [combine_blocks(self._value_label, self, b=0)],
            )

    def _warn_outside_bounds(self, default):
        logger.warning(
            f"Default value {default} was outside of the ({self.minimum()}:{self.maximum()}) range"
        )

    def _update_slider(self):
        """Update slider when value is changed."""
        try:
            if self._value_label.text() == "":
                return

            value = float(self._value_label.text()) * self._divide_factor

            if value < self.minimum():
                self.slider_value = self.minimum()
                return
            if value > self.maximum():
                self.slider_value = self.maximum()
                return

            self.slider_value = value
        except Exception as e:
            logger.error(e)

    def _update_value_label(self):
        """Update label, to connect to when slider is dragged."""
        try:
            self._value_label.setText(str(self.value_text))
        except Exception as e:
            logger.error(e)

    @property
    def tooltips(self):
        """Get the tooltip of the slider."""
        return self.toolTip()

    @tooltips.setter
    def tooltips(self, tooltip: str):
        """Set the tooltip of the slider and label."""
        self.setToolTip(tooltip)
        self._value_label.setToolTip(tooltip)

        if self.label is not None:
            self.label.setToolTip(tooltip)

    @property
    def slider_value(self):
        """Get value of the slider divided by self._divide_factor to implement floats in Slider."""
        if self._divide_factor == 1.0:
            return self.value()

        try:
            return self.value() / self._divide_factor
        except ZeroDivisionError as e:
            logger.error(f"Divide factor cannot be 0 for Slider : {e}")
            raise ZeroDivisionError from (e)

    @property
    def value_text(self):
        """Get value of the slide bar as string."""
        return str(self.slider_value)

    @slider_value.setter
    def slider_value(self, value: int):
        """Set a value (int) divided by self._divide_factor."""
        if value < self.minimum() or value > self.maximum():
            logger.error(
                ValueError(
                    f"The value for the slider ({value}) cannot be out of ({self.minimum()};{self.maximum()}) "
                )
            )

        try:
            self.setValue(int(value))

            divided = value / self._divide_factor
            if self._divide_factor == 1.0:
                divided = int(divided)
            self._value_label.setText(str(divided))
        except Exception as e:
            logger.error(e)

slider_value property writable

slider_value

Get value of the slider divided by self._divide_factor to implement floats in Slider.

tooltips property writable

tooltips

Get the tooltip of the slider.

value_text property

value_text

Get value of the slide bar as string.

__init__

__init__(lower: int = 0, upper: int = 100, step: int = 1, default: int = 0, divide_factor: float = 1.0, parent=None, orientation=Qt.Horizontal, text_label: str = None)

Creates a slider to select a value between lower and upper, with a step.

Source code in napari_cellseg3d/interface.py
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
def __init__(
    self,
    lower: int = 0,
    upper: int = 100,
    step: int = 1,
    default: int = 0,
    divide_factor: float = 1.0,
    parent=None,
    orientation=Qt.Horizontal,
    text_label: str = None,
):
    """Creates a slider to select a value between lower and upper, with a step."""
    super().__init__(orientation, parent)

    if upper <= lower:
        raise ValueError("The minimum value cannot be below the maximum one")

    self.setMaximum(upper)
    self.setMinimum(lower)
    self.setSingleStep(step)

    self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

    self.label = None
    self.container = ContainerWidget(
        # parent=self.parent,
        b=0,
    )

    self._divide_factor = divide_factor
    self._value_label = QLineEdit(self.value_text, parent=self)

    if self._divide_factor == 1:
        self._value_label.setFixedWidth(20)
    elif self._divide_factor == 10:
        self._value_label.setFixedWidth(30)
    else:
        self._value_label.setFixedWidth(50)
    self._value_label.setAlignment(Qt.AlignCenter)
    self._value_label.setSizePolicy(
        QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed
    )

    self._value_label.setStyleSheet(
        f"background-color: {napari_param_grey};"
        f"border-radius: 5px;"
        "min - height: 12px;"
        "min - width: 12px;"
    )

    if text_label is not None:
        self.label = make_label(text_label, parent=self)

    if default < lower:
        self._warn_outside_bounds(default)
        default = lower
    elif default > upper:
        self._warn_outside_bounds(default)
        default = upper

    self.valueChanged.connect(self._update_value_label)
    self._value_label.textChanged.connect(self._update_slider)

    self.slider_value = default

    self._build_container()

set_visibility

set_visibility(visible: bool)

Sets the visibility of the slider and its label.

Source code in napari_cellseg3d/interface.py
550
551
552
553
554
def set_visibility(self, visible: bool):
    """Sets the visibility of the slider and its label."""
    self.container.setVisible(visible)
    self.setVisible(visible)
    self.label.setVisible(visible)

UtilsDropdown

Singleton class for use in instantiating only one Utility dropdown menu that can be accessed from the plugin.

Methods:

Name Description
dropdown_menu_call

Calls the utility dropdown menu at the location of a CTRL+right-click.

show_utils_menu

Shows the context menu for utilities. Use with dropdown_menu_call.

Source code in napari_cellseg3d/interface.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
class UtilsDropdown(metaclass=utils.Singleton):
    """Singleton class for use in instantiating only one Utility dropdown menu that can be accessed from the plugin."""

    caller_widget = None

    def dropdown_menu_call(self, widget, event):
        """Calls the utility dropdown menu at the location of a CTRL+right-click."""
        # ### DEBUG ### #
        # print(event.modifiers)
        # print("menu call")
        # print(widget)
        # print(self)
        ##################
        if self.caller_widget is None:
            self.caller_widget = widget

        if event.button == 2 and "control" in event.modifiers:
            dragged = False
            yield
            # on move
            while event.type == "mouse_move":
                # print(event.position)
                dragged = True
                yield
            # on release
            if dragged:
                # print("drag end")
                pass
            else:
                # print("clicked!")
                if widget is self.caller_widget:
                    # print(f"authorized widget {widget} to show menu")
                    pos = QCursor.pos()
                    self.show_utils_menu(widget, pos)
                # else:
                # print(f"blocked widget {widget} from opening utils")

    def show_utils_menu(self, widget, event):
        """Shows the context menu for utilities. Use with dropdown_menu_call.

        Args:
            widget: widget to show context menu in
            event: mouse press event
        """
        from napari_cellseg3d.code_plugins.plugin_utilities import (
            UTILITIES_WIDGETS,
        )

        menu = QMenu(widget.window())
        menu.setStyleSheet(f"background-color: {napari_grey}; color: white;")

        actions = []
        for title in UTILITIES_WIDGETS:
            a = menu.addAction(f"Utilities : {title}")
            actions.append(a)

        action = menu.exec_(event)

        for possible_action in actions:
            if action == possible_action:
                text = possible_action.text().split(": ")[1]
                widget = UTILITIES_WIDGETS[text](widget._viewer)
                widget._viewer.window.add_dock_widget(widget, name=text)

dropdown_menu_call

dropdown_menu_call(widget, event)

Calls the utility dropdown menu at the location of a CTRL+right-click.

Source code in napari_cellseg3d/interface.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def dropdown_menu_call(self, widget, event):
    """Calls the utility dropdown menu at the location of a CTRL+right-click."""
    # ### DEBUG ### #
    # print(event.modifiers)
    # print("menu call")
    # print(widget)
    # print(self)
    ##################
    if self.caller_widget is None:
        self.caller_widget = widget

    if event.button == 2 and "control" in event.modifiers:
        dragged = False
        yield
        # on move
        while event.type == "mouse_move":
            # print(event.position)
            dragged = True
            yield
        # on release
        if dragged:
            # print("drag end")
            pass
        else:
            # print("clicked!")
            if widget is self.caller_widget:
                # print(f"authorized widget {widget} to show menu")
                pos = QCursor.pos()
                self.show_utils_menu(widget, pos)

show_utils_menu

show_utils_menu(widget, event)

Shows the context menu for utilities. Use with dropdown_menu_call.

Parameters:

Name Type Description Default
widget

widget to show context menu in

required
event

mouse press event

required
Source code in napari_cellseg3d/interface.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def show_utils_menu(self, widget, event):
    """Shows the context menu for utilities. Use with dropdown_menu_call.

    Args:
        widget: widget to show context menu in
        event: mouse press event
    """
    from napari_cellseg3d.code_plugins.plugin_utilities import (
        UTILITIES_WIDGETS,
    )

    menu = QMenu(widget.window())
    menu.setStyleSheet(f"background-color: {napari_grey}; color: white;")

    actions = []
    for title in UTILITIES_WIDGETS:
        a = menu.addAction(f"Utilities : {title}")
        actions.append(a)

    action = menu.exec_(event)

    for possible_action in actions:
        if action == possible_action:
            text = possible_action.text().split(": ")[1]
            widget = UTILITIES_WIDGETS[text](widget._viewer)
            widget._viewer.window.add_dock_widget(widget, name=text)

add_blank

add_blank(widget, layout=None)

Adds a space between consecutive buttons/labels in a layout when building a widget.

Parameters:

Name Type Description Default
widget QWidget

widget to add blank in

required
layout QLayout

layout to add blank in

None

Returns:

Name Type Description
QLabel

blank label

Source code in napari_cellseg3d/interface.py
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
def add_blank(widget, layout=None):
    """Adds a space between consecutive buttons/labels in a layout when building a widget.

    Args:
        widget (QWidget): widget to add blank in
        layout (QLayout): layout to add blank in

    Returns:
        QLabel : blank label
    """
    blank = QLabel("", widget)
    if layout is not None:
        layout.addWidget(blank, alignment=ABS_AL)
    return blank

add_label

add_label(widget, label, label_before=True, horizontal=True)

Adds a label to a widget.

Parameters:

Name Type Description Default
widget

The widget to add the label to

required
label

The label to add

required
label_before

If True, the label is added before the widget. If False, the label is added after the widget

True
horizontal

If True, the label and widget are added horizontally. If False, they are added vertically

True
Source code in napari_cellseg3d/interface.py
339
340
341
342
343
344
345
346
347
348
349
350
def add_label(widget, label, label_before=True, horizontal=True):
    """Adds a label to a widget.

    Args:
        widget: The widget to add the label to
        label: The label to add
        label_before: If True, the label is added before the widget. If False, the label is added after the widget
        horizontal: If True, the label and widget are added horizontally. If False, they are added vertically
    """
    if label_before:
        return combine_blocks(widget, label, horizontal=horizontal)
    return combine_blocks(label, widget, horizontal=horizontal)

add_widgets

add_widgets(layout, widgets, alignment=LEFT_AL)

Adds all widgets in the list to layout, with the specified alignment.

If alignment is None, no alignment is set.

Parameters:

Name Type Description Default
layout

layout to add widgets in

required
widgets

list of QWidgets to add to layout

required
alignment

any valid Qt.AlignmentFlag, see aliases at beginning of interface.py. If None, uses default of addWidget

LEFT_AL
Source code in napari_cellseg3d/interface.py
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
def add_widgets(layout, widgets, alignment=LEFT_AL):
    """Adds all widgets in the list to layout, with the specified alignment.

    If alignment is None, no alignment is set.

    Args:
        layout: layout to add widgets in
        widgets: list of QWidgets to add to layout
        alignment: any valid Qt.AlignmentFlag, see aliases at beginning of interface.py. If None, uses default of addWidget
    """
    if alignment is None:
        for w in widgets:
            layout.addWidget(w)
    else:
        for w in widgets:
            layout.addWidget(w, alignment=alignment)

combine_blocks

combine_blocks(right_or_below, left_or_above, min_spacing=0, horizontal=True, l=11, t=3, r=11, b=11)

Combines two QWidget objects and puts them side by side (first on the left/top and second on the right/bottom depending on "horizontal").

Weird argument names due the initial implementation of it. # TODO maybe fix arg names or refactor.

Parameters:

Name Type Description Default
left_or_above QWidget

First widget, to be added on the left/above of "second"

required
right_or_below QWidget

Second widget, to be displayed right/below of "first"

required
min_spacing int

Minimum spacing between the two widgets (from the start of label to the start of button)

0
horizontal bool

whether to stack widgets vertically (False) or horizontally (True)

True
l int

left spacing in pixels

11
t int

top spacing in pixels

3
r int

right spacing in pixels

11
b int

bottom spacing in pixels

11

Returns:

Name Type Description
QWidget

new QWidget containing the merged widget and label

Source code in napari_cellseg3d/interface.py
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
def combine_blocks(  # TODO FIXME PLEASE this is a horrible design
    right_or_below,
    left_or_above,
    min_spacing=0,
    horizontal=True,
    l=11,
    t=3,
    r=11,
    b=11,
):
    """Combines two QWidget objects and puts them side by side (first on the left/top and second on the right/bottom depending on "horizontal").

       Weird argument names due the initial implementation of it.  # TODO maybe fix arg names or refactor.

    Args:
        left_or_above (QWidget): First widget, to be added on the left/above of "second"
        right_or_below (QWidget): Second widget, to be displayed right/below of "first"
        min_spacing (int): Minimum spacing between the two widgets (from the start of label to the start of button)
        horizontal (bool): whether to stack widgets vertically (False) or horizontally (True)
        l (int): left spacing in pixels
        t (int): top spacing in pixels
        r (int): right spacing in pixels
        b (int): bottom spacing in pixels

    Returns:
        QWidget: new QWidget containing the merged widget and label
    """
    temp_widget = QWidget()
    temp_widget.setSizePolicy(
        QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding
    )

    temp_layout = QGridLayout()
    if horizontal:
        temp_widget.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Maximum)
        temp_layout.setColumnMinimumWidth(0, min_spacing)
        c1, c2, r1, r2 = 0, 1, 0, 0
        temp_layout.setContentsMargins(l, t, r, b)  # determines spacing between widgets
    else:
        temp_widget.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.MinimumExpanding)
        temp_layout.setRowMinimumHeight(0, min_spacing)
        c1, c2, r1, r2 = 0, 0, 0, 1
        temp_layout.setContentsMargins(l, t, r, b)  # determines spacing between widgets
    # temp_layout.setColumnMinimumWidth(1,100)
    # temp_layout.setSizeConstraint(QLayout.SetMinAndMaxSize)

    temp_layout.addWidget(left_or_above, r1, c1)  # , alignment=LEFT_AL)
    # temp_layout.addStretch(100)
    temp_layout.addWidget(right_or_below, r2, c2)  # , alignment=LEFT_AL)
    temp_widget.setLayout(temp_layout)
    return temp_widget

handle_adjust_errors

handle_adjust_errors(widget, warning_type, context, msg: str)

Qt message handler that attempts to react to errors when setting the window size and resizes the main window.

Source code in napari_cellseg3d/interface.py
103
104
105
def handle_adjust_errors(widget, warning_type, context, msg: str):
    """Qt message handler that attempts to react to errors when setting the window size and resizes the main window."""
    pass

handle_adjust_errors_wrapper

handle_adjust_errors_wrapper(widget)

Returns a callable that can be used with qInstallMessageHandler directly.

Source code in napari_cellseg3d/interface.py
126
127
128
def handle_adjust_errors_wrapper(widget):
    """Returns a callable that can be used with qInstallMessageHandler directly."""
    return partial(handle_adjust_errors, widget)

make_group

make_group(title, l=7, t=20, r=7, b=11, parent=None)

Creates a group widget and layout, with a header (title) and content margins for top/left/right/bottom L, T, R, B (in pixels).

Group widget and layout returned will have a Fixed size policy.

Parameters:

Name Type Description Default
title str

Title of the group

required
l int

left margin

7
t int

top margin

20
r int

right margin

7
b int

bottom margin

11
parent (QWidget)

parent widget. If None, no parent is set

required
Source code in napari_cellseg3d/interface.py
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
def make_group(title, l=7, t=20, r=7, b=11, parent=None):
    """Creates a group widget and layout, with a header (`title`) and content margins for top/left/right/bottom `L, T, R, B` (in pixels).

    Group widget and layout returned will have a Fixed size policy.

    Args:
        title (str): Title of the group
        l (int): left margin
        t (int): top margin
        r (int): right margin
        b (int): bottom margin
        parent (QWidget) : parent widget. If None, no parent is set
    """
    group = GroupedWidget(title, l, t, r, b, parent=parent)
    layout = group.layout

    return group, layout

make_label

make_label(name, parent=None)

Creates a QLabel.

Parameters:

Name Type Description Default
name

string with name

required
parent

parent widget

None

Returns: created label

Source code in napari_cellseg3d/interface.py
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
def make_label(name, parent=None):  # TODO update to child class
    """Creates a QLabel.

    Args:
        name: string with name
        parent: parent widget

    Returns: created label

    """
    if parent is not None:
        label = QLabel(name, parent)
        if SHOW_LABELS_DEBUG_TOOLTIP:
            label.setToolTip(f"{label}")
    else:
        label = QLabel(name)
        if SHOW_LABELS_DEBUG_TOOLTIP:
            label.setToolTip(f"{label}")
    return label

make_n_spinboxes

make_n_spinboxes(class_, n: int = 2, min_value=0, max_value=10, default=0, step=1, parent: Optional[QWidget] = None, fixed: Optional[bool] = True)

Creates n increment counters with the specified parameters.

Parameters:

Name Type Description Default
class_

QSpinBox or QDoubleSpinbox

required
n int

number of increment counters to create

2
min_value Optional[int]

minimum value, defaults to 0

0
max_value Optional[int]

maximum value, defaults to 10

10
default Optional[int]

default value, defaults to 0

0
step Optional[int]

step value, defaults to 1

1
parent Optional[QWidget]

parent widget, defaults to None

None
fixed bool

if True, sets the QSizePolicy of the spinbox to Fixed

True
Source code in napari_cellseg3d/interface.py
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
def make_n_spinboxes(
    class_,
    n: int = 2,
    min_value=0,
    max_value=10,
    default=0,
    step=1,
    parent: Optional[QWidget] = None,
    fixed: Optional[bool] = True,
):
    """Creates n increment counters with the specified parameters.

    Args:
        class_ : QSpinBox or QDoubleSpinbox
        n (int): number of increment counters to create
        min_value (Optional[int]): minimum value, defaults to 0
        max_value (Optional[int]): maximum value, defaults to 10
        default (Optional[int]): default value, defaults to 0
        step (Optional[int]): step value, defaults to 1
        parent: parent widget, defaults to None
        fixed (bool): if True, sets the QSizePolicy of the spinbox to Fixed
    """
    if n <= 1:
        raise ValueError("Cannot make less than 2 spin boxes")

    boxes = []
    for _i in range(n):
        box = class_(min_value, max_value, default, step, parent, fixed)
        boxes.append(box)
    return boxes

open_directory

open_directory(path)

Opens a folder in the OS file browser.

Parameters:

Name Type Description Default
path str | Path

folder to open

required

Returns:

Name Type Description
bool

False if the folder does not exist or could not be opened.

Source code in napari_cellseg3d/interface.py
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
def open_directory(path):
    """Opens a folder in the OS file browser.

    Args:
        path (str | Path): folder to open

    Returns:
        bool: False if the folder does not exist or could not be opened.
    """
    path = Path(path)
    if not path.is_dir():
        logger.warning(f"Cannot open {path} : folder does not exist")
        return False
    return QDesktopServices.openUrl(QUrl.fromLocalFile(str(path.resolve())))

open_file_dialog

open_file_dialog(widget, possible_paths: list = (), file_extension: str = 'Image file (*.tif *.tiff)')

Opens a window to choose a file directory using QFileDialog.

Parameters:

Name Type Description Default
widget QWidget

Widget to display file dialog in

required
possible_paths str

Paths that may have been chosen before, can be a string

()
load_as_folder bool

Whether to open a folder or a single file. If True, will allow opening folder as a single file (2D stack interpreted as 3D)

required
file_extension str

The description and file extension to load (format : "Description (*.example1 *.example2)"). Default "Image file (*.tif *.tiff)"

'Image file (*.tif *.tiff)'

Returns:

Name Type Description
str

chosen file path

Source code in napari_cellseg3d/interface.py
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
def open_file_dialog(
    widget,
    possible_paths: list = (),
    file_extension: str = "Image file (*.tif *.tiff)",
):
    """Opens a window to choose a file directory using QFileDialog.

    Args:
        widget (QWidget): Widget to display file dialog in
        possible_paths (str): Paths that may have been chosen before, can be a string
        or an array of strings containing the paths
        load_as_folder (bool): Whether to open a folder or a single file. If True, will allow opening folder as a single file (2D stack interpreted as 3D)
        file_extension (str): The description and file extension to load (format : ``"Description (*.example1 *.example2)"``). Default ``"Image file (*.tif *.tiff)"``

    Returns:
        str : chosen file path
    """
    default_path = utils.parse_default_path(possible_paths)

    return QFileDialog.getOpenFileName(
        widget, "Choose file", default_path, file_extension
    )

open_folder_dialog

open_folder_dialog(widget, possible_paths: list = ())

Opens a window to choose a directory using QFileDialog.

Parameters:

Name Type Description Default
widget QWidget

Widget to display file dialog in

required
possible_paths str

Paths that may have been chosen before, can be a string

()

Returns:

Name Type Description
str

chosen directory path

Source code in napari_cellseg3d/interface.py
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
def open_folder_dialog(
    widget,
    possible_paths: list = (),
):
    """Opens a window to choose a directory using QFileDialog.

    Args:
        widget (QWidget): Widget to display file dialog in
        possible_paths (str): Paths that may have been chosen before, can be a string
        or an array of strings containing the paths

    Returns:
        str : chosen directory path
    """
    default_path = utils.parse_default_path(possible_paths)

    logger.debug(f"Default : {default_path}")
    return QFileDialog.getExistingDirectory(
        widget,
        "Open directory",
        default_path,  # + "/.."
    )

open_url

open_url(url)

Opens the url given as a string in OS default browser using :py:func:QDesktopServices.openUrl.

Parameters:

Name Type Description Default
url str

Url to be opened

required
Source code in napari_cellseg3d/interface.py
1535
1536
1537
1538
1539
1540
1541
def open_url(url):
    """Opens the url given as a string in OS default browser using :py:func:`QDesktopServices.openUrl`.

    Args:
        url (str): Url to be opened
    """
    QDesktopServices.openUrl(QUrl(url, QUrl.TolerantMode))

set_hover_color

set_hover_color(button, color=coral_red)

Makes a push button glow with color while hovered; other states keep the napari theme.

Parameters:

Name Type Description Default
button QPushButton

the Qt button (for a magicgui widget, pass its .native)

required
color str

hover background color

coral_red
Source code in napari_cellseg3d/interface.py
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
def set_hover_color(button, color=coral_red):
    """Makes a push button glow with `color` while hovered; other states keep the napari theme.

    Args:
        button (QPushButton): the Qt button (for a magicgui widget, pass its `.native`)
        color (str): hover background color
    """
    button.setStyleSheet(
        f"QPushButton:hover {{ background-color: {color}; color: white; }}"
    )

set_spinbox

set_spinbox(box, min_value=0, max_value=10, default=0, step=1, fixed: Optional[bool] = True)

Sets the parameters of a QSpinBox or QDoubleSpinBox.

Parameters:

Name Type Description Default
box

QSpinBox or QDoubleSpinBox

required
min_value

minimum value, defaults to 0

required
max_value

maximum value, defaults to 10

required
default

default value, defaults to 0

required
step

step value, defaults to 1

required
fixed bool

if True, sets the QSizePolicy of the spinbox to Fixed

True
Source code in napari_cellseg3d/interface.py
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
def set_spinbox(
    box,
    min_value=0,
    max_value=10,
    default=0,
    step=1,
    fixed: Optional[bool] = True,
):
    """Sets the parameters of a QSpinBox or QDoubleSpinBox.

    Args:
        box : QSpinBox or QDoubleSpinBox
        min_value : minimum value, defaults to 0
        max_value : maximum value, defaults to 10
        default :  default value, defaults to 0
        step : step value, defaults to 1
        fixed (bool): if True, sets the QSizePolicy of the spinbox to Fixed
    """
    box.setMinimum(min_value)
    box.setMaximum(max_value)
    box.setSingleStep(step)
    box.setValue(default)

    if fixed:
        box.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

toggle_visibility

toggle_visibility(checkbox, widget)

Toggles the visibility of a widget based on the status of a checkbox.

Parameters:

Name Type Description Default
checkbox

The QCheckbox that determines whether to show or not

required
widget

The widget to hide or show

required
Source code in napari_cellseg3d/interface.py
329
330
331
332
333
334
335
336
def toggle_visibility(checkbox, widget):
    """Toggles the visibility of a widget based on the status of a checkbox.

    Args:
        checkbox: The QCheckbox that determines whether to show or not
        widget: The widget to hide or show
    """
    widget.setVisible(checkbox.isChecked())