code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def remove_dock_widget(self, widget: QWidget, menu=None):
"""Removes specified dock widget.
If a QDockWidget is not provided, the existing QDockWidgets will be
searched for one whose inner widget (``.widget()``) is the provided
``widget``.
Parameters
----------
... | Removes specified dock widget.
If a QDockWidget is not provided, the existing QDockWidgets will be
searched for one whose inner widget (``.widget()``) is the provided
``widget``.
Parameters
----------
widget : QWidget | str
If widget == 'all', all docked wid... | remove_dock_widget | python | napari/napari | src/napari/_qt/qt_main_window.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_main_window.py | BSD-3-Clause |
def add_function_widget(
self,
function,
*,
magic_kwargs=None,
name: str = '',
area=None,
allowed_areas=None,
shortcut=_sentinel,
):
"""Turn a function into a dock widget via magicgui.
Parameters
----------
function : c... | Turn a function into a dock widget via magicgui.
Parameters
----------
function : callable
Function that you want to add.
magic_kwargs : dict, optional
Keyword arguments to :func:`magicgui.magicgui` that
can be used to specify widget.
name : s... | add_function_widget | python | napari/napari | src/napari/_qt/qt_main_window.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_main_window.py | BSD-3-Clause |
def geometry(self) -> tuple[int, int, int, int]:
"""Get the geometry of the widget
Returns
-------
left : int
X coordinate of the upper left border.
top : int
Y coordinate of the upper left border.
width : int
Width of the rectangle sh... | Get the geometry of the widget
Returns
-------
left : int
X coordinate of the upper left border.
top : int
Y coordinate of the upper left border.
width : int
Width of the rectangle shape of the window.
height : int
Height o... | geometry | python | napari/napari | src/napari/_qt/qt_main_window.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_main_window.py | BSD-3-Clause |
def show(self, *, block=False):
"""Resize, show, and bring forward the window.
Raises
------
RuntimeError
If the viewer.window has already been closed and deleted.
"""
settings = get_settings()
try:
self._qt_window.show(block=block)
... | Resize, show, and bring forward the window.
Raises
------
RuntimeError
If the viewer.window has already been closed and deleted.
| show | python | napari/napari | src/napari/_qt/qt_main_window.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_main_window.py | BSD-3-Clause |
def activate(self):
"""Make the viewer the currently active window."""
self._qt_window.raise_() # for macOS
self._qt_window.activateWindow() # for Windows | Make the viewer the currently active window. | activate | python | napari/napari | src/napari/_qt/qt_main_window.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_main_window.py | BSD-3-Clause |
def _status_changed(self, event):
"""Update status bar.
Parameters
----------
event : napari.utils.event.Event
The napari event that triggered this method.
"""
if not hasattr(self, '_qt_window'):
return
if isinstance(event.value, str):
... | Update status bar.
Parameters
----------
event : napari.utils.event.Event
The napari event that triggered this method.
| _status_changed | python | napari/napari | src/napari/_qt/qt_main_window.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_main_window.py | BSD-3-Clause |
def _screenshot(
self,
size: tuple[int, int] | None = None,
scale: float | None = None,
flash: bool = True,
canvas_only: bool = False,
fit_to_data_extent: bool = False,
) -> 'QImage':
"""Capture screenshot of the currently displayed viewer.
Parameters... | Capture screenshot of the currently displayed viewer.
Parameters
----------
flash : bool
Flag to indicate whether flash animation should be shown after
the screenshot was captured.
size : tuple of two ints, optional
Size (resolution height x width) of... | _screenshot | python | napari/napari | src/napari/_qt/qt_main_window.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_main_window.py | BSD-3-Clause |
def export_figure(
self,
path: str | None = None,
scale: float = 1,
flash=True,
) -> np.ndarray:
"""Export an image of the full extent of the displayed layer data.
This function finds a tight boundary around the data, resets the view
around that boundary (and... | Export an image of the full extent of the displayed layer data.
This function finds a tight boundary around the data, resets the view
around that boundary (and, when scale=1, such that 1 captured pixel is
equivalent to one data pixel), takes a screenshot, then restores the
previous zoom... | export_figure | python | napari/napari | src/napari/_qt/qt_main_window.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_main_window.py | BSD-3-Clause |
def export_rois(
self,
rois: list[np.ndarray],
paths: str | Path | list[str | Path] | None = None,
scale: float | None = None,
):
"""Export the given rectangular rois to specified file paths.
For each shape, moves the camera to the center of the shape
and adj... | Export the given rectangular rois to specified file paths.
For each shape, moves the camera to the center of the shape
and adjust the canvas size to fit the shape.
Note: The shape height and width can be of type float.
However, the canvas size only accepts a tuple of integers.
T... | export_rois | python | napari/napari | src/napari/_qt/qt_main_window.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_main_window.py | BSD-3-Clause |
def screenshot(
self, path=None, size=None, scale=None, flash=True, canvas_only=False
):
"""Take currently displayed viewer and convert to an image array.
Parameters
----------
path : str, Path
Filename for saving screenshot image.
size : tuple (int, int)... | Take currently displayed viewer and convert to an image array.
Parameters
----------
path : str, Path
Filename for saving screenshot image.
size : tuple (int, int)
Size (resolution) of the screenshot. By default, the currently displayed size.
Only use... | screenshot | python | napari/napari | src/napari/_qt/qt_main_window.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_main_window.py | BSD-3-Clause |
def close(self):
"""Close the viewer window and cleanup sub-widgets."""
# Someone is closing us twice? Only try to delete self._qt_window
# if we still have one.
if hasattr(self, '_qt_window'):
self._teardown()
self._qt_viewer.close()
self._qt_window.c... | Close the viewer window and cleanup sub-widgets. | close | python | napari/napari | src/napari/_qt/qt_main_window.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_main_window.py | BSD-3-Clause |
def _screenshot_dialog(self):
"""Save screenshot of current display with viewer, default .png"""
from napari._qt.dialogs.screenshot_dialog import ScreenshotDialog
from napari.utils.history import get_save_history, update_save_history
hist = get_save_history()
dial = ScreenshotDi... | Save screenshot of current display with viewer, default .png | _screenshot_dialog | python | napari/napari | src/napari/_qt/qt_main_window.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_main_window.py | BSD-3-Clause |
def _npe2_decode_selected_filter(
ext_str: str, selected_filter: str, writers: Sequence[WriterContribution]
) -> WriterContribution | None:
"""Determine the writer that should be invoked to save data.
When npe2 can be imported, resolves a selected file extension
string into a specific writer. Otherwise... | Determine the writer that should be invoked to save data.
When npe2 can be imported, resolves a selected file extension
string into a specific writer. Otherwise, returns None.
| _npe2_decode_selected_filter | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _extension_string_for_layers(
layers: Sequence[Layer],
) -> tuple[str, list[WriterContribution]]:
"""Return an extension string and the list of corresponding writers.
The extension string is a ";;" delimeted string of entries. Each entry
has a brief description of the file type and a list of extens... | Return an extension string and the list of corresponding writers.
The extension string is a ";;" delimeted string of entries. Each entry
has a brief description of the file type and a list of extensions.
The writers, when provided, are the npe2.manifest.io.WriterContribution
objects. There is one writ... | _extension_string_for_layers | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _update_dask_cache_settings(
dask_setting: DaskSettings | Event = None,
):
"""Update dask cache to match settings."""
if not dask_setting:
return
if not isinstance(dask_setting, DaskSettings):
dask_setting = get_settings().application.dask
enabled... | Update dask cache to match settings. | _update_dask_cache_settings | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def viewerButtons(self) -> QtViewerButtons:
"""Button controls for the napari viewer."""
if self._viewerButtons is None:
self._viewerButtons = QtViewerButtons(self.viewer)
return self._viewerButtons | Button controls for the napari viewer. | viewerButtons | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def dockLayerList(self) -> QtViewerDockWidget:
"""QWidget wrapped in a QDockWidget with forwarded viewer events."""
if self._dockLayerList is None:
layerList = QWidget()
layerList.setObjectName('layerList')
layerListLayout = QVBoxLayout()
layerListLayout.a... | QWidget wrapped in a QDockWidget with forwarded viewer events. | dockLayerList | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _bind_shortcuts(self):
"""Bind shortcuts stored in SETTINGS to actions."""
for action, shortcuts in get_settings().shortcuts.shortcuts.items():
action_manager.unbind_shortcut(action)
for shortcut in shortcuts:
action_manager.bind_shortcut(action, shortcut) | Bind shortcuts stored in SETTINGS to actions. | _bind_shortcuts | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _create_performance_dock_widget(self):
"""Create the dock widget that shows performance metrics."""
if perf.perf_config is not None:
return QtViewerDockWidget(
self,
QtPerformance(),
name=trans._('performance'),
area='bottom... | Create the dock widget that shows performance metrics. | _create_performance_dock_widget | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _weakref_if_possible(self, obj):
"""Create a weakref to obj.
Parameters
----------
obj : object
Cannot create weakrefs to many Python built-in datatypes such as
list, dict, str.
From https://docs.python.org/3/library/weakref.html: "Objects which
... | Create a weakref to obj.
Parameters
----------
obj : object
Cannot create weakrefs to many Python built-in datatypes such as
list, dict, str.
From https://docs.python.org/3/library/weakref.html: "Objects which
support weak references include clas... | _weakref_if_possible | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def add_to_console_backlog(self, variables):
"""Save variables for pushing to console when it is instantiated.
This function will create weakrefs when possible to avoid holding on to
too much memory unnecessarily.
Parameters
----------
variables : dict, str or list/tupl... | Save variables for pushing to console when it is instantiated.
This function will create weakrefs when possible to avoid holding on to
too much memory unnecessarily.
Parameters
----------
variables : dict, str or list/tuple of str
The variables to inject into the co... | add_to_console_backlog | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _get_console(self) -> QtConsole | None:
"""Function to setup console.
Returns
-------
console : QtConsole or None
The napari console.
Notes
_____
_get_console extracted to separate function to simplify testing.
"""
try:
... | Function to setup console.
Returns
-------
console : QtConsole or None
The napari console.
Notes
_____
_get_console extracted to separate function to simplify testing.
| _get_console | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def console(self):
"""QtConsole: iPython console terminal integrated into the napari GUI."""
if self._console is None:
self.console = self._get_console()
self._console_backlog = []
return self._console | QtConsole: iPython console terminal integrated into the napari GUI. | console | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _on_slice_ready(self, event):
"""Callback connected to `viewer._layer_slicer.events.ready`.
Provides updates after slicing using the slice response data.
This only gets triggered on the async slicing path.
"""
responses: dict[weakref.ReferenceType[Layer], Any] = event.value
... | Callback connected to `viewer._layer_slicer.events.ready`.
Provides updates after slicing using the slice response data.
This only gets triggered on the async slicing path.
| _on_slice_ready | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _on_active_change(self):
"""When active layer changes change keymap handler."""
self._key_map_handler.keymap_providers = (
[self.viewer]
if self.viewer.layers.selection.active is None
else [self.viewer.layers.selection.active, self.viewer]
) | When active layer changes change keymap handler. | _on_active_change | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _update_camera_depth(self):
"""When the layer extents change, update the camera depth.
The camera depth is the difference between the near clipping plane
and the far clipping plane in a scene. If they are set too high
relative to the actual depth of a scene, precision issues can ari... | When the layer extents change, update the camera depth.
The camera depth is the difference between the near clipping plane
and the far clipping plane in a scene. If they are set too high
relative to the actual depth of a scene, precision issues can arise
in the depth of objects in the s... | _update_camera_depth | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _add_layer(self, layer):
"""When a layer is added, set its parent and order.
Parameters
----------
layer : napari.layers.Layer
Layer to be added.
"""
vispy_layer = create_vispy_layer(layer)
# QtPoll is experimental.
if self._qt_poll is no... | When a layer is added, set its parent and order.
Parameters
----------
layer : napari.layers.Layer
Layer to be added.
| _add_layer | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _remove_invalid_chars(self, selected_layer_name):
"""Removes invalid characters from selected layer name to suggest a filename.
Parameters
----------
selected_layer_name : str
The selected napari layer name.
Returns
-------
suggested_name : str
... | Removes invalid characters from selected layer name to suggest a filename.
Parameters
----------
selected_layer_name : str
The selected napari layer name.
Returns
-------
suggested_name : str
Suggested name from input selected layer name, without... | _remove_invalid_chars | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _save_layers_dialog(self, selected=False):
"""Save layers (all or selected) to disk, using ``LayerList.save()``.
Parameters
----------
selected : bool
If True, only layers that are selected in the viewer will be saved.
By default, all layers are saved.
... | Save layers (all or selected) to disk, using ``LayerList.save()``.
Parameters
----------
selected : bool
If True, only layers that are selected in the viewer will be saved.
By default, all layers are saved.
| _save_layers_dialog | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _screenshot(self, flash=True):
"""Capture a screenshot of the Vispy canvas.
Parameters
----------
flash : bool
Flag to indicate whether flash animation should be shown after
the screenshot was captured.
"""
img = self.canvas.screenshot()
... | Capture a screenshot of the Vispy canvas.
Parameters
----------
flash : bool
Flag to indicate whether flash animation should be shown after
the screenshot was captured.
| _screenshot | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def screenshot(self, path=None, flash=True) -> np.ndarray:
"""Take currently displayed screen and convert to an image array.
Parameters
----------
path : str
Filename for saving screenshot image.
flash : bool
Flag to indicate whether flash animation shoul... | Take currently displayed screen and convert to an image array.
Parameters
----------
path : str
Filename for saving screenshot image.
flash : bool
Flag to indicate whether flash animation should be shown after
the screenshot was captured.
Ret... | screenshot | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _screenshot_dialog(self):
"""Save screenshot of current display, default .png"""
hist = get_save_history()
dial = ScreenshotDialog(self.screenshot, self, hist[0], hist)
if dial.exec_():
update_save_history(dial.selectedFiles()[0]) | Save screenshot of current display, default .png | _screenshot_dialog | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _open_file_dialog_uni(self, caption: str) -> list[str]:
"""
Open dialog to get list of files from user
"""
dlg = QFileDialog()
hist = get_open_history()
dlg.setHistory(hist)
open_kwargs = {
'parent': self,
'caption': caption,
}... |
Open dialog to get list of files from user
| _open_file_dialog_uni | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _open_folder_dialog(self, choose_plugin=False):
"""Add a folder of files from the menubar."""
dlg = QFileDialog()
hist = get_open_history()
dlg.setHistory(hist)
folder = dlg.getExistingDirectory(
self,
trans._('Select folder...'),
hist[0],... | Add a folder of files from the menubar. | _open_folder_dialog | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _qt_open(
self,
filenames: list[str],
stack: bool | list[list[str]],
choose_plugin: bool = False,
plugin: str | None = None,
layer_type: str | None = None,
**kwargs,
):
"""Open files, potentially popping reader dialog for plugin selection.
... | Open files, potentially popping reader dialog for plugin selection.
Call ViewerModel.open and catch errors that could
be fixed by user making a plugin choice.
Parameters
----------
filenames : List[str]
paths to open
choose_plugin : bool
True if ... | _qt_open | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def toggle_console_visibility(self, event=None):
"""Toggle console visible and not visible.
Imports the console the first time it is requested.
"""
if in_ipython() or in_jupyter():
return
# force instantiation of console if not already instantiated
_ = self.... | Toggle console visible and not visible.
Imports the console the first time it is requested.
| toggle_console_visibility | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def dragEnterEvent(self, event):
"""Ignore event if not dragging & dropping a file or URL to open.
Using event.ignore() here allows the event to pass through the
parent widget to its child widget, otherwise the parent widget
would catch the event and not pass it on to the child widget.
... | Ignore event if not dragging & dropping a file or URL to open.
Using event.ignore() here allows the event to pass through the
parent widget to its child widget, otherwise the parent widget
would catch the event and not pass it on to the child widget.
Parameters
----------
... | dragEnterEvent | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _set_drag_status(self):
"""Set dedicated status message when dragging files into viewer"""
self.viewer.status = trans._(
'Hold <Alt> key to open plugin selection. Hold <Shift> to open files as stack.'
) | Set dedicated status message when dragging files into viewer | _set_drag_status | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _image_from_clipboard(self):
"""Insert image from clipboard as a new layer if clipboard contains an image or link."""
cb = QGuiApplication.clipboard()
if cb.mimeData().hasImage():
image = cb.image()
if image.isNull():
return
arr = QImg2arra... | Insert image from clipboard as a new layer if clipboard contains an image or link. | _image_from_clipboard | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def dropEvent(self, event):
"""Add local files and web URLS with drag and drop.
For each file, attempt to open with existing associated reader
(if available). If no reader is associated or opening fails,
and more than one reader is available, open dialog and ask
user to choose a... | Add local files and web URLS with drag and drop.
For each file, attempt to open with existing associated reader
(if available). If no reader is associated or opening fails,
and more than one reader is available, open dialog and ask
user to choose among available readers. User can choose... | dropEvent | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def closeEvent(self, event):
"""Cleanup and close.
Parameters
----------
event : qtpy.QtCore.QCloseEvent
Event from the Qt context.
"""
if self._layers is not None:
# do not create layerlist if it does not exist yet.
self.layers.close(... | Cleanup and close.
Parameters
----------
event : qtpy.QtCore.QCloseEvent
Event from the Qt context.
| closeEvent | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _create_qt_poll(parent: QObject, camera: Camera) -> QtPoll | None:
"""Create and return a QtPoll instance, if needed.
Create a QtPoll instance for the monitor.
Monitor needs QtPoll to poll for incoming messages. This might be
temporary until we can process incoming messages with a dedicated
th... | Create and return a QtPoll instance, if needed.
Create a QtPoll instance for the monitor.
Monitor needs QtPoll to poll for incoming messages. This might be
temporary until we can process incoming messages with a dedicated
thread.
Parameters
----------
parent : QObject
Parent Qt ob... | _create_qt_poll | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _create_remote_manager(layers: LayerList, qt_poll) -> RemoteManager | None:
"""Create and return a RemoteManager instance, if we need one.
Parameters
----------
layers : LayersList
The viewer's layers.
qt_poll : QtPoll
The viewer's QtPoll instance.
"""
if not config.moni... | Create and return a RemoteManager instance, if we need one.
Parameters
----------
layers : LayersList
The viewer's layers.
qt_poll : QtPoll
The viewer's QtPoll instance.
| _create_remote_manager | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def _in_napari(n: int, frame: FrameType):
"""
Determines whether we are in napari by looking at:
1) the frames modules names:
2) the min_depth
"""
if n < 2:
return True
# in-n-out is used in napari for dependency injection.
for pref in {'napari.', 'in_n_out.'}:
if... |
Determines whether we are in napari by looking at:
1) the frames modules names:
2) the min_depth
| _in_napari | python | napari/napari | src/napari/_qt/qt_viewer.py | https://github.com/napari/napari/blob/master/src/napari/_qt/qt_viewer.py | BSD-3-Clause |
def str_to_qbytearray(string: str) -> QByteArray:
"""Convert a string to a QbyteArray.
Used for restoring the state of the main window.
Parameters
----------
string : str
State string.
"""
if len(string) < len(QBYTE_FLAG) or not is_qbyte(string):
raise ValueError(
... | Convert a string to a QbyteArray.
Used for restoring the state of the main window.
Parameters
----------
string : str
State string.
| str_to_qbytearray | python | napari/napari | src/napari/_qt/utils.py | https://github.com/napari/napari/blob/master/src/napari/_qt/utils.py | BSD-3-Clause |
def QImg2array(img) -> np.ndarray:
"""Convert QImage to an array.
Parameters
----------
img : qtpy.QtGui.QImage
QImage to be converted.
Returns
-------
arr : array
Numpy array of type ubyte and shape (h, w, 4). Index [0, 0] is the
upper-left corner of the rendered r... | Convert QImage to an array.
Parameters
----------
img : qtpy.QtGui.QImage
QImage to be converted.
Returns
-------
arr : array
Numpy array of type ubyte and shape (h, w, 4). Index [0, 0] is the
upper-left corner of the rendered region.
| QImg2array | python | napari/napari | src/napari/_qt/utils.py | https://github.com/napari/napari/blob/master/src/napari/_qt/utils.py | BSD-3-Clause |
def qt_signals_blocked(obj):
"""Context manager to temporarily block signals from `obj`"""
previous = obj.blockSignals(True)
try:
yield
finally:
obj.blockSignals(previous) | Context manager to temporarily block signals from `obj` | qt_signals_blocked | python | napari/napari | src/napari/_qt/utils.py | https://github.com/napari/napari/blob/master/src/napari/_qt/utils.py | BSD-3-Clause |
def event_hook_removed():
"""Context manager to temporarily remove the PyQt5 input hook"""
from qtpy import QtCore
if hasattr(QtCore, 'pyqtRemoveInputHook'):
QtCore.pyqtRemoveInputHook()
try:
yield
finally:
if hasattr(QtCore, 'pyqtRestoreInputHook'):
QtCore.pyqtR... | Context manager to temporarily remove the PyQt5 input hook | event_hook_removed | python | napari/napari | src/napari/_qt/utils.py | https://github.com/napari/napari/blob/master/src/napari/_qt/utils.py | BSD-3-Clause |
def set_widgets_enabled_with_opacity(
parent: QWidget, widgets: Iterable[QWidget], enabled: bool
):
"""Set enabled state on some widgets. If not enabled, decrease opacity."""
for widget in widgets:
op = QGraphicsOpacityEffect(parent)
op.setOpacity(0.5)
# Only enable opacity effect wh... | Set enabled state on some widgets. If not enabled, decrease opacity. | set_widgets_enabled_with_opacity | python | napari/napari | src/napari/_qt/utils.py | https://github.com/napari/napari/blob/master/src/napari/_qt/utils.py | BSD-3-Clause |
def drag_with_pixmap(list_widget: QListWidget) -> QDrag:
"""Create a QDrag object with a pixmap of the currently select list item.
This method is useful when you have a QListWidget that displays custom
widgets for each QListWidgetItem instance in the list (usually by calling
``QListWidget.setItemWidget... | Create a QDrag object with a pixmap of the currently select list item.
This method is useful when you have a QListWidget that displays custom
widgets for each QListWidgetItem instance in the list (usually by calling
``QListWidget.setItemWidget(item, widget)``). When used in a
``QListWidget.startDrag``... | drag_with_pixmap | python | napari/napari | src/napari/_qt/utils.py | https://github.com/napari/napari/blob/master/src/napari/_qt/utils.py | BSD-3-Clause |
def combine_widgets(
widgets: QWidget | Sequence[QWidget], vertical: bool = False
) -> QWidget:
"""Combine a list of widgets into a single QWidget with Layout.
Parameters
----------
widgets : QWidget or sequence of QWidget
A widget or a list of widgets to combine.
vertical : bool, optio... | Combine a list of widgets into a single QWidget with Layout.
Parameters
----------
widgets : QWidget or sequence of QWidget
A widget or a list of widgets to combine.
vertical : bool, optional
Whether the layout should be QVBoxLayout or not, by default
QHBoxLayout is used
Re... | combine_widgets | python | napari/napari | src/napari/_qt/utils.py | https://github.com/napari/napari/blob/master/src/napari/_qt/utils.py | BSD-3-Clause |
def add_flash_animation(
widget: QWidget, duration: int = 300, color: Array = (0.5, 0.5, 0.5, 0.5)
):
"""Add flash animation to widget to highlight certain action (e.g. taking a screenshot).
Parameters
----------
widget : QWidget
Any Qt widget.
duration : int
Duration of the fla... | Add flash animation to widget to highlight certain action (e.g. taking a screenshot).
Parameters
----------
widget : QWidget
Any Qt widget.
duration : int
Duration of the flash animation.
color : Array
Color of the flash animation. By default, we use light gray.
| add_flash_animation | python | napari/napari | src/napari/_qt/utils.py | https://github.com/napari/napari/blob/master/src/napari/_qt/utils.py | BSD-3-Clause |
def remove_flash_animation(widget_ref: weakref.ref[QWidget]):
"""Remove flash animation from widget.
Parameters
----------
widget_ref : QWidget
Any Qt widget.
"""
if widget_ref() is None:
return
widget = widget_ref()
try:
widget.setGraphicsEffect(None)
wi... | Remove flash animation from widget.
Parameters
----------
widget_ref : QWidget
Any Qt widget.
| remove_flash_animation | python | napari/napari | src/napari/_qt/utils.py | https://github.com/napari/napari/blob/master/src/napari/_qt/utils.py | BSD-3-Clause |
def _maybe_allow_interrupt(qapp):
"""
This manager allows to terminate a plot by sending a SIGINT. It is
necessary because the running Qt backend prevents Python interpreter to
run and process signals (i.e., to raise KeyboardInterrupt exception). To
solve this one needs to somehow wake up the interp... |
This manager allows to terminate a plot by sending a SIGINT. It is
necessary because the running Qt backend prevents Python interpreter to
run and process signals (i.e., to raise KeyboardInterrupt exception). To
solve this one needs to somehow wake up the interpreter and make it close
the plot wind... | _maybe_allow_interrupt | python | napari/napari | src/napari/_qt/utils.py | https://github.com/napari/napari/blob/master/src/napari/_qt/utils.py | BSD-3-Clause |
def qt_might_be_rich_text(text) -> bool:
"""
Check if a text might be rich text in a cross-binding compatible way.
"""
if qtpy.PYSIDE2:
from qtpy.QtGui import Qt as Qt_
else:
from qtpy.QtCore import Qt as Qt_
try:
return Qt_.mightBeRichText(text)
except AttributeErro... |
Check if a text might be rich text in a cross-binding compatible way.
| qt_might_be_rich_text | python | napari/napari | src/napari/_qt/utils.py | https://github.com/napari/napari/blob/master/src/napari/_qt/utils.py | BSD-3-Clause |
def get_color(
color: str | np.ndarray | QColor | None = None,
mode: ColorMode = ColorMode.HEX,
) -> np.ndarray | None:
"""
Helper function to get a color from q QColorDialog.
Parameters
----------
color : str | np.ndarray | QColor | None
Initial color to display in the dialog. Colo... |
Helper function to get a color from q QColorDialog.
Parameters
----------
color : str | np.ndarray | QColor | None
Initial color to display in the dialog. Color will be automatically converted to QColor.
mode : ColorMode
Mode to return the color in (hex, array, QColor).
Return... | get_color | python | napari/napari | src/napari/_qt/utils.py | https://github.com/napari/napari/blob/master/src/napari/_qt/utils.py | BSD-3-Clause |
def flags(self, index: QModelIndex) -> Qt.ItemFlags:
"""Returns the item flags for the given `index`.
This describes the properties of a given item in the model. We set
them to be editable, checkable, draggable, droppable, etc...
If index is not a list, we additionally set `Qt.ItemNeve... | Returns the item flags for the given `index`.
This describes the properties of a given item in the model. We set
them to be editable, checkable, draggable, droppable, etc...
If index is not a list, we additionally set `Qt.ItemNeverHasChildren`
(for optimization). Editable models must r... | flags | python | napari/napari | src/napari/_qt/containers/qt_axis_model.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/qt_axis_model.py | BSD-3-Clause |
def dropMimeData(self, data, action, destRow, col, parent):
"""Handle destination row for dropping with reversed indices."""
row = 0 if destRow == -1 else self.sourceModel().rowCount() - destRow
return self.sourceModel().dropMimeData(data, action, row, col, parent) | Handle destination row for dropping with reversed indices. | dropMimeData | python | napari/napari | src/napari/_qt/containers/qt_layer_list.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/qt_layer_list.py | BSD-3-Clause |
def keyPressEvent(self, e: QKeyEvent | None) -> None:
"""Override Qt event to pass events to the viewer."""
if e is None:
return
# capture arrows with modifiers so they are handled by Viewer keybindings
if (e.key() == Qt.Key.Key_Up or e.key() == Qt.Key.Key_Down) and (
... | Override Qt event to pass events to the viewer. | keyPressEvent | python | napari/napari | src/napari/_qt/containers/qt_layer_list.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/qt_layer_list.py | BSD-3-Clause |
def data(self, index: QModelIndex, role: Qt.ItemDataRole):
"""Return data stored under ``role`` for the item at ``index``."""
if not index.isValid():
return None
layer = self.getItem(index)
viewer = current_viewer()
layer_loaded = layer.loaded
# Playback with ... | Return data stored under ``role`` for the item at ``index``. | data | python | napari/napari | src/napari/_qt/containers/qt_layer_model.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/qt_layer_model.py | BSD-3-Clause |
def all_loaded(self):
"""Return if all the layers are loaded."""
return all(
self.index(row, 0).data(LoadedRole)
for row in range(self.rowCount())
) | Return if all the layers are loaded. | all_loaded | python | napari/napari | src/napari/_qt/containers/qt_layer_model.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/qt_layer_model.py | BSD-3-Clause |
def mimeData(self, indices: list[QModelIndex]) -> Optional['QMimeData']:
"""Return an object containing serialized data from `indices`.
If the list of indexes is empty, or there are no supported MIME types,
None is returned rather than a serialized empty list.
"""
if not indices... | Return an object containing serialized data from `indices`.
If the list of indexes is empty, or there are no supported MIME types,
None is returned rather than a serialized empty list.
| mimeData | python | napari/napari | src/napari/_qt/containers/qt_list_model.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/qt_list_model.py | BSD-3-Clause |
def data(self, index: QModelIndex, role: Qt.ItemDataRole):
"""Return data stored under ``role`` for the item at ``index``.
A given class:`QModelIndex` can store multiple types of data, each with
its own "ItemDataRole".
"""
item = self.getItem(index)
if role == Qt.ItemDat... | Return data stored under ``role`` for the item at ``index``.
A given class:`QModelIndex` can store multiple types of data, each with
its own "ItemDataRole".
| data | python | napari/napari | src/napari/_qt/containers/qt_tree_model.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/qt_tree_model.py | BSD-3-Clause |
def index(
self, row: int, column: int = 0, parent: QModelIndex | None = None
) -> QModelIndex:
"""Return a QModelIndex for item at `row`, `column` and `parent`."""
# NOTE: self.createIndex(row, col, object) will create a model index
# that *stores* a pointer to the object, which ca... | Return a QModelIndex for item at `row`, `column` and `parent`. | index | python | napari/napari | src/napari/_qt/containers/qt_tree_model.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/qt_tree_model.py | BSD-3-Clause |
def getItem(self, index: QModelIndex) -> NodeType:
"""Return python object for a given `QModelIndex`.
An invalid `QModelIndex` will return the root object.
"""
if index.isValid():
item = index.internalPointer()
if item is not None:
return item
... | Return python object for a given `QModelIndex`.
An invalid `QModelIndex` will return the root object.
| getItem | python | napari/napari | src/napari/_qt/containers/qt_tree_model.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/qt_tree_model.py | BSD-3-Clause |
def parent(self, index: QModelIndex) -> QModelIndex:
"""Return the parent of the model item with the given ``index``.
If the item has no parent, an invalid QModelIndex is returned.
"""
if not index.isValid():
return QModelIndex() # null index
parentItem = self.getI... | Return the parent of the model item with the given ``index``.
If the item has no parent, an invalid QModelIndex is returned.
| parent | python | napari/napari | src/napari/_qt/containers/qt_tree_model.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/qt_tree_model.py | BSD-3-Clause |
def mimeData(self, indices: list[QModelIndex]) -> Optional['NodeMimeData']:
"""Return an object containing serialized data from `indices`.
The format used to describe the encoded data is obtained from the
mimeTypes() function. The implementation uses the default MIME type
returned by th... | Return an object containing serialized data from `indices`.
The format used to describe the encoded data is obtained from the
mimeTypes() function. The implementation uses the default MIME type
returned by the default implementation of mimeTypes(). If you
reimplement mimeTypes() in your... | mimeData | python | napari/napari | src/napari/_qt/containers/qt_tree_model.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/qt_tree_model.py | BSD-3-Clause |
def _redecorate_root(self, parent: QModelIndex = None, *_):
"""Add a branch/arrow column only if there are Groups in the root.
This makes the tree fall back to looking like a simple list if there
are no lists in the root level.
"""
if not parent or not parent.isValid():
... | Add a branch/arrow column only if there are Groups in the root.
This makes the tree fall back to looking like a simple list if there
are no lists in the root level.
| _redecorate_root | python | napari/napari | src/napari/_qt/containers/qt_tree_view.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/qt_tree_view.py | BSD-3-Clause |
def data(self, index: QModelIndex, role: Qt.ItemDataRole) -> Any:
"""Returns data stored under `role` for the item at `index`.
A given `QModelIndex` can store multiple types of data, each
with its own "ItemDataRole". ItemType-specific subclasses will likely
want to customize this metho... | Returns data stored under `role` for the item at `index`.
A given `QModelIndex` can store multiple types of data, each
with its own "ItemDataRole". ItemType-specific subclasses will likely
want to customize this method (and likely `setData` as well) for
different data roles.
s... | data | python | napari/napari | src/napari/_qt/containers/_base_item_model.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_base_item_model.py | BSD-3-Clause |
def flags(self, index: QModelIndex) -> Qt.ItemFlags:
"""Returns the item flags for the given `index`.
This describes the properties of a given item in the model. We set
them to be editable, checkable, dragable, droppable, etc...
If index is not a list, we additionally set `Qt.ItemNever... | Returns the item flags for the given `index`.
This describes the properties of a given item in the model. We set
them to be editable, checkable, dragable, droppable, etc...
If index is not a list, we additionally set `Qt.ItemNeverHasChildren`
(for optimization). Editable models must re... | flags | python | napari/napari | src/napari/_qt/containers/_base_item_model.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_base_item_model.py | BSD-3-Clause |
def rowCount(self, parent: QModelIndex | None = None) -> int:
"""Returns the number of rows under the given parent.
When the parent is valid it means that rowCount is returning the number
of children of parent.
"""
if parent is None:
parent = QModelIndex()
tr... | Returns the number of rows under the given parent.
When the parent is valid it means that rowCount is returning the number
of children of parent.
| rowCount | python | napari/napari | src/napari/_qt/containers/_base_item_model.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_base_item_model.py | BSD-3-Clause |
def setRoot(self, root: SelectableEventedList[ItemType]):
"""Call during __init__, to set the python model and connections"""
if not isinstance(root, SelectableEventedList):
raise TypeError(
trans._(
'root must be an instance of {class_name}',
... | Call during __init__, to set the python model and connections | setRoot | python | napari/napari | src/napari/_qt/containers/_base_item_model.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_base_item_model.py | BSD-3-Clause |
def _on_begin_inserting(self, event):
"""Begins a row insertion operation.
See Qt documentation:
https://doc.qt.io/qt-5/qabstractitemmodel.html#beginInsertRows
"""
par, idx = self._split_nested_index(event.index)
self.beginInsertRows(par, idx, idx) | Begins a row insertion operation.
See Qt documentation:
https://doc.qt.io/qt-5/qabstractitemmodel.html#beginInsertRows
| _on_begin_inserting | python | napari/napari | src/napari/_qt/containers/_base_item_model.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_base_item_model.py | BSD-3-Clause |
def _on_begin_removing(self, event):
"""Begins a row removal operation.
See Qt documentation:
https://doc.qt.io/qt-5/qabstractitemmodel.html#beginRemoveRows
"""
par, idx = self._split_nested_index(event.index)
self.beginRemoveRows(par, idx, idx) | Begins a row removal operation.
See Qt documentation:
https://doc.qt.io/qt-5/qabstractitemmodel.html#beginRemoveRows
| _on_begin_removing | python | napari/napari | src/napari/_qt/containers/_base_item_model.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_base_item_model.py | BSD-3-Clause |
def _on_begin_moving(self, event):
"""Begins a row move operation.
See Qt documentation:
https://doc.qt.io/qt-5/qabstractitemmodel.html#beginMoveRows
"""
src_par, src_idx = self._split_nested_index(event.index)
dest_par, dest_idx = self._split_nested_index(event.new_inde... | Begins a row move operation.
See Qt documentation:
https://doc.qt.io/qt-5/qabstractitemmodel.html#beginMoveRows
| _on_begin_moving | python | napari/napari | src/napari/_qt/containers/_base_item_model.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_base_item_model.py | BSD-3-Clause |
def currentChanged(
self: QAbstractItemView, current: QModelIndex, previous: QModelIndex
):
"""The Qt current item has changed. Update the python model."""
self._root.selection._current = current.data(ItemRole)
return super().currentChanged(current, previous) | The Qt current item has changed. Update the python model. | currentChanged | python | napari/napari | src/napari/_qt/containers/_base_item_view.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_base_item_view.py | BSD-3-Clause |
def selectionChanged(
self: QAbstractItemView,
selected: QItemSelection,
deselected: QItemSelection,
):
"""The Qt Selection has changed. Update the python model."""
sel = {i.data(ItemRole) for i in selected.indexes()}
desel = {i.data(ItemRole) for i in deselected.inde... | The Qt Selection has changed. Update the python model. | selectionChanged | python | napari/napari | src/napari/_qt/containers/_base_item_view.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_base_item_view.py | BSD-3-Clause |
def setRoot(self, root: SelectableEventedList[ItemType]):
"""Call during __init__, to set the python model."""
self._root = root
self.setModel(create_model(root, self))
# connect selection events
root.selection.events.changed.connect(self._on_py_selection_change)
root.se... | Call during __init__, to set the python model. | setRoot | python | napari/napari | src/napari/_qt/containers/_base_item_view.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_base_item_view.py | BSD-3-Clause |
def _on_py_current_change(self, event: Event):
"""The python model current item has changed. Update the Qt view."""
sm = self.selectionModel()
if not event.value:
sm.clearCurrentIndex()
else:
idx = index_of(self.model(), event.value)
sm.setCurrentIndex... | The python model current item has changed. Update the Qt view. | _on_py_current_change | python | napari/napari | src/napari/_qt/containers/_base_item_view.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_base_item_view.py | BSD-3-Clause |
def _on_py_selection_change(self, event: Event):
"""The python model selection has changed. Update the Qt view."""
sm = self.selectionModel()
for is_selected, idx in chain(
zip(repeat(sm.SelectionFlag.Select), event.added),
zip(repeat(sm.SelectionFlag.Deselect), event.rem... | The python model selection has changed. Update the Qt view. | _on_py_selection_change | python | napari/napari | src/napari/_qt/containers/_base_item_view.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_base_item_view.py | BSD-3-Clause |
def _sync_selection_models(self):
"""Clear and re-sync the Qt selection view from the python selection."""
sel_model = self.selectionModel()
selection = QItemSelection()
for i in self._root.selection:
idx = index_of(self.model(), i)
selection.select(idx, idx)
... | Clear and re-sync the Qt selection view from the python selection. | _sync_selection_models | python | napari/napari | src/napari/_qt/containers/_base_item_view.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_base_item_view.py | BSD-3-Clause |
def index_of(model: QAbstractItemModel, obj: ItemType) -> QModelIndex:
"""Find the `QModelIndex` for a given object in the model."""
fl = Qt.MatchFlag.MatchExactly | Qt.MatchFlag.MatchRecursive
hits = model.match(
model.index(0, 0, QModelIndex()),
Qt.ItemDataRole.UserRole,
obj,
... | Find the `QModelIndex` for a given object in the model. | index_of | python | napari/napari | src/napari/_qt/containers/_base_item_view.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_base_item_view.py | BSD-3-Clause |
def create_view(
obj: SelectableEventedList | Group, parent: QWidget | None = None
):
"""Create a `QtListView`, or `QtNodeTreeView` for `obj`.
Parameters
----------
obj : SelectableEventedList or Group
The python object for which to creat a QtView.
parent : QWidget, optional
Opt... | Create a `QtListView`, or `QtNodeTreeView` for `obj`.
Parameters
----------
obj : SelectableEventedList or Group
The python object for which to creat a QtView.
parent : QWidget, optional
Optional parent widget, by default None
Returns
-------
Union[QtListView, QtNodeTreeVie... | create_view | python | napari/napari | src/napari/_qt/containers/_factory.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_factory.py | BSD-3-Clause |
def create_model(
obj: SelectableEventedList | Group, parent: QWidget | None = None
):
"""Create a `QtListModel`, or `QtNodeTreeModel` for `obj`.
Parameters
----------
obj : SelectableEventedList or Group
The python object for which to creat a QtView.
parent : QWidget, optional
... | Create a `QtListModel`, or `QtNodeTreeModel` for `obj`.
Parameters
----------
obj : SelectableEventedList or Group
The python object for which to creat a QtView.
parent : QWidget, optional
Optional parent widget, by default None
Returns
-------
Union[QtListModel, QtNodeTree... | create_model | python | napari/napari | src/napari/_qt/containers/_factory.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_factory.py | BSD-3-Clause |
def paint(
self,
painter: QPainter,
option: QStyleOptionViewItem,
index: QtCore.QModelIndex,
):
"""Paint the item in the model at `index`."""
# update the icon based on layer type
option.textElideMode = Qt.TextElideMode.ElideMiddle
self.get_layer_icon(... | Paint the item in the model at `index`. | paint | python | napari/napari | src/napari/_qt/containers/_layer_delegate.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_layer_delegate.py | BSD-3-Clause |
def get_layer_icon(
self, option: QStyleOptionViewItem, index: QtCore.QModelIndex
):
"""Add the appropriate QIcon to the item based on the layer type."""
layer = index.data(ItemRole)
if layer is None:
return
if hasattr(layer, 'is_group') and layer.is_group(): # f... | Add the appropriate QIcon to the item based on the layer type. | get_layer_icon | python | napari/napari | src/napari/_qt/containers/_layer_delegate.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_layer_delegate.py | BSD-3-Clause |
def createEditor(
self,
parent: QWidget,
option: QStyleOptionViewItem,
index: QtCore.QModelIndex,
) -> QWidget:
"""User has double clicked on layer name."""
# necessary for geometry, otherwise editor takes up full width.
self.get_layer_icon(option, index)
... | User has double clicked on layer name. | createEditor | python | napari/napari | src/napari/_qt/containers/_layer_delegate.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_layer_delegate.py | BSD-3-Clause |
def editorEvent(
self,
event: QtCore.QEvent,
model: QtCore.QAbstractItemModel,
option: QStyleOptionViewItem,
index: QtCore.QModelIndex,
) -> bool:
"""Called when an event has occured in the editor.
This can be used to customize how the delegate handles mouse/... | Called when an event has occured in the editor.
This can be used to customize how the delegate handles mouse/key events
| editorEvent | python | napari/napari | src/napari/_qt/containers/_layer_delegate.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_layer_delegate.py | BSD-3-Clause |
def _show_on_alt_click_hide_others(
self,
model: QtCore.QAbstractItemModel,
index: QtCore.QModelIndex,
) -> QtCore.QAbstractItemModel:
"""On alt/option click of a layer show the layer, hide other layers,
to be restored once a layer is alt/option-clicked a second time.
... | On alt/option click of a layer show the layer, hide other layers,
to be restored once a layer is alt/option-clicked a second time.
| _show_on_alt_click_hide_others | python | napari/napari | src/napari/_qt/containers/_layer_delegate.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_layer_delegate.py | BSD-3-Clause |
def show_context_menu(self, index, model, pos: QPoint, parent):
"""Show the layerlist context menu.
To add a new item to the menu, update the _LAYER_ACTIONS dict.
"""
if not hasattr(self, '_context_menu'):
self._context_menu = build_qmodel_menu(
MenuId.LAYERLI... | Show the layerlist context menu.
To add a new item to the menu, update the _LAYER_ACTIONS dict.
| show_context_menu | python | napari/napari | src/napari/_qt/containers/_layer_delegate.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_layer_delegate.py | BSD-3-Clause |
def test_drag_and_drop_layers(qtbot):
"""
Test drag and drop actions with pyautogui to change layer list order.
Notes:
* For this test to pass locally on macOS, you need to give the Terminal/iTerm
application accessibility permissions:
`System Settings > Privacy & Security >... |
Test drag and drop actions with pyautogui to change layer list order.
Notes:
* For this test to pass locally on macOS, you need to give the Terminal/iTerm
application accessibility permissions:
`System Settings > Privacy & Security > Accessibility`
See https://github.c... | test_drag_and_drop_layers | python | napari/napari | src/napari/_qt/containers/_tests/test_qt_layer_list.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_tests/test_qt_layer_list.py | BSD-3-Clause |
def test_move_multiple(sources, dest, expectation):
"""Test that models stay in sync with complicated moves.
This uses mimeData to simulate drag/drop operations.
"""
root = SelectableEventedList(map(T, range(8)))
root.events = Mock(wraps=root.events)
assert root != expectation
qt_tree = Qt... | Test that models stay in sync with complicated moves.
This uses mimeData to simulate drag/drop operations.
| test_move_multiple | python | napari/napari | src/napari/_qt/containers/_tests/test_qt_list.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_tests/test_qt_list.py | BSD-3-Clause |
def _recursive_make_group(lst, level=0):
"""Make a Tree of Group/Node objects from a nested list."""
out = []
for item in lst:
if isinstance(item, list):
out.append(_recursive_make_group(item, level=level + 1))
else:
out.append(Node(name=str(item)))
return Group(o... | Make a Tree of Group/Node objects from a nested list. | _recursive_make_group | python | napari/napari | src/napari/_qt/containers/_tests/test_qt_tree.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_tests/test_qt_tree.py | BSD-3-Clause |
def test_qt_tree_model_deletion(qapp):
"""Test that we can delete items from a QTreeModel"""
root = _recursive_make_group([0, 1, [20, [210, 211], 22], 3, 4])
qt_tree = QtNodeTreeModel(root)
_assert_models_synced(root, qt_tree)
del root[2, 1]
e = _recursive_make_group([0, 1, [20, 22], 3, 4])
... | Test that we can delete items from a QTreeModel | test_qt_tree_model_deletion | python | napari/napari | src/napari/_qt/containers/_tests/test_qt_tree.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_tests/test_qt_tree.py | BSD-3-Clause |
def test_qt_tree_model_insertion(qapp):
"""Test that we can append and insert items to a QTreeModel."""
root = _recursive_make_group([0, 1, [20, [210, 211], 22], 3, 4])
qt_tree = QtNodeTreeModel(root)
_assert_models_synced(root, qt_tree)
root[2, 1].append(Node(name='212'))
e = _recursive_make_gr... | Test that we can append and insert items to a QTreeModel. | test_qt_tree_model_insertion | python | napari/napari | src/napari/_qt/containers/_tests/test_qt_tree.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_tests/test_qt_tree.py | BSD-3-Clause |
def test_flags(tree_model):
"""Some sanity checks on retrieving flags for nested items"""
assert not tree_model.hasIndex(5, 0, tree_model.index(1))
last = tree_model._root.pop()
tree_model._root[1].append(last)
assert tree_model.hasIndex(5, 0, tree_model.index(1))
idx = tree_model.index(5, 0, tr... | Some sanity checks on retrieving flags for nested items | test_flags | python | napari/napari | src/napari/_qt/containers/_tests/test_qt_tree.py | https://github.com/napari/napari/blob/master/src/napari/_qt/containers/_tests/test_qt_tree.py | BSD-3-Clause |
def _rebuild_dialog(self):
"""Removes settings not to be exposed to user and creates dialog pages."""
# FIXME: this dialog should not need to know about the plugin manager
from napari.plugins import plugin_manager
self._starting_pm_order = plugin_manager.call_order()
self._start... | Removes settings not to be exposed to user and creates dialog pages. | _rebuild_dialog | python | napari/napari | src/napari/_qt/dialogs/preferences_dialog.py | https://github.com/napari/napari/blob/master/src/napari/_qt/dialogs/preferences_dialog.py | BSD-3-Clause |
def _add_page(self, field: 'ModelField'):
"""Builds the preferences widget using the json schema builder.
Parameters
----------
field : ModelField
subfield for which to create a page.
"""
from napari._vendor.qt_json_builder.qt_jsonschema_form import (
... | Builds the preferences widget using the json schema builder.
Parameters
----------
field : ModelField
subfield for which to create a page.
| _add_page | python | napari/napari | src/napari/_qt/dialogs/preferences_dialog.py | https://github.com/napari/napari/blob/master/src/napari/_qt/dialogs/preferences_dialog.py | BSD-3-Clause |
def _get_page_dict(self, field: 'ModelField') -> tuple[dict, dict]:
"""Provides the schema, set of values for each setting, and the
properties for each setting."""
ftype = cast('BaseModel', field.type_)
# TODO make custom shortcuts dialog to properly capture new
# functiona... | Provides the schema, set of values for each setting, and the
properties for each setting. | _get_page_dict | python | napari/napari | src/napari/_qt/dialogs/preferences_dialog.py | https://github.com/napari/napari/blob/master/src/napari/_qt/dialogs/preferences_dialog.py | BSD-3-Clause |
def _restore_default_dialog(self):
"""Launches dialog to confirm restore settings choice."""
prev = QApplication.instance().testAttribute(
Qt.ApplicationAttribute.AA_DontUseNativeDialogs
)
QApplication.instance().setAttribute(
Qt.ApplicationAttribute.AA_DontUseNat... | Launches dialog to confirm restore settings choice. | _restore_default_dialog | python | napari/napari | src/napari/_qt/dialogs/preferences_dialog.py | https://github.com/napari/napari/blob/master/src/napari/_qt/dialogs/preferences_dialog.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.