We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[Qt6] AttributeError when renaming a layer
## 🐛 Bug

This seems to be yet another small Qt6 issue related to enum name changes.

## To Reproduce

Steps to reproduce the behavior:

1. Launch napari from a Qt6 environment
2. Open a file or otherwise create a new layer
3. Double click the layer to rename it, triggering the exception

```
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
File ~/src/napari/napari/_qt/containers/_layer_delegate.py:141, in LayerDelegate.createEditor(self=<napari._qt.containers._layer_delegate.LayerDelegate object>, parent=<PyQt6.QtWidgets.QWidget object>, option=<PyQt6.QtWidgets.QStyleOptionViewItem object>, index=<PyQt6.QtCore.QModelIndex object>)
    138 editor = super().createEditor(parent, option, index)
    139 # make sure editor has same alignment as the display name
    140 editor.setAlignment(
--> 141     Qt.Alignment(index.data(Qt.ItemDataRole.TextAlignmentRole))
        editor = <PyQt6.QtWidgets.QLineEdit object at 0x2aaa3e4d0>
        index = <PyQt6.QtCore.QModelIndex object at 0x16b74ee30>
        Qt = <class 'PyQt6.QtCore.Qt'>
        Qt.ItemDataRole.TextAlignmentRole = <ItemDataRole.TextAlignmentRole: 7>
    142 )
    143 return editor

AttributeError: type object 'Qt' has no attribute 'Alignment'
```

## Expected behavior

Double-clicking the layer should allow editing the layer name and not raise an exception.

## Environment

napari: 0.5.0a2.dev129+g0dfb37b47.d20230518
Platform: macOS-13.3.1-arm64-arm-64bit
System: MacOS 13.3.1
Python: 3.10.9 (main, Feb 3 2023, 15:40:08) [Clang 14.0.0 (clang-1400.0.29.202)]
Qt: 6.5.0
PyQt6: 
NumPy: 1.24.1
SciPy: 1.10.0
Dask: 2023.1.1
VisPy: 0.12.3.dev45+dirty
magicgui: 0.6.1
superqt: unknown
in-n-out: 0.1.6
app-model: 0.1.1.dev3+gdf48c9d
npe2: 0.6.2

OpenGL:
- GL version: 2.1 Metal - 83.1
- MAX_TEXTURE_SIZE: 16384

Screens:
- screen 1: resolution 2560x1440, scale 1.0

Settings path:
- /Users/aandersoniii/Library/Application Support/napari/venv_640f7def1935afdf07a142187e645430c6d70fe6/settings.yaml

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `napari/_qt/containers/_layer_delegate.py`
Content:
```
1 """
2 General rendering flow:
3 
4 1. The List/Tree view needs to display or edit an index in the model...
5 2. It gets the ``itemDelegate``
6     a. A custom delegate can be set with ``setItemDelegate``
7     b. ``QStyledItemDelegate`` is the default delegate for all Qt item views,
8        and is installed upon them when they are created.
9 3. ``itemDelegate.paint`` is called on the index being displayed
10 4. Each index in the model has various data elements (i.e. name, image, etc..),
11    each of which has a "data role".  A model should return the appropriate data
12    for each role by reimplementing ``QAbstractItemModel.data``.
13     a. `QStyledItemDelegate` implements display and editing for the most common
14        datatypes expected by users, including booleans, integers, and strings.
15     b. If the delegate does not support painting of the data types you need or
16        you want to customize the drawing of items, you need to subclass
17        ``QStyledItemDelegate``, and reimplement ``paint()`` and possibly
18        ``sizeHint()``.
19     c. When reimplementing ``paint()``, one typically handles the datatypes
20        they would like to draw and uses the superclass implementation for other
21        types.
22 5. The default implementation of ``QStyledItemDelegate.paint`` paints the item
23    using the view's ``QStyle`` (which is, by default, an OS specific style...
24    but see ``QCommonStyle`` for a generic implementation)
25     a. It is also possible to override the view's style, using either a
26     subclass of ``QCommonStyle``, for a platform-independent look and feel, or
27     ``QProxyStyle``, which let's you override only certain stylistic elements
28     on any platform, falling back to the system default otherwise.
29     b. ``QStyle`` paints various elements using methods like ``drawPrimitive``
30        and ``drawControl``.  These can be overridden for very fine control.
31 6. It is hard to use stylesheets with custom ``QStyles``... but it's possible
32    to style sub-controls in ``QAbstractItemView`` (such as ``QTreeView``):
33    https://doc.qt.io/qt-5/stylesheet-reference.html#list-of-sub-controls
34 
35 """
36 from __future__ import annotations
37 
38 from typing import TYPE_CHECKING
39 
40 from qtpy.QtCore import QPoint, QSize, Qt
41 from qtpy.QtGui import QMouseEvent, QPixmap
42 from qtpy.QtWidgets import QStyledItemDelegate
43 
44 from napari._app_model.constants import MenuId
45 from napari._app_model.context import get_context
46 from napari._qt._qapp_model import build_qmodel_menu
47 from napari._qt.containers._base_item_model import ItemRole
48 from napari._qt.containers.qt_layer_model import ThumbnailRole
49 from napari._qt.qt_resources import QColoredSVGIcon
50 
51 if TYPE_CHECKING:
52     from qtpy import QtCore
53     from qtpy.QtGui import QPainter
54     from qtpy.QtWidgets import QStyleOptionViewItem, QWidget
55 
56     from napari.components.layerlist import LayerList
57 
58 
59 class LayerDelegate(QStyledItemDelegate):
60     """A QItemDelegate specialized for painting Layer objects.
61 
62     In Qt's `Model/View architecture
63     <https://doc.qt.io/qt-5/model-view-programming.html>`_. A *delegate* is an
64     object that controls the visual rendering (and editing widgets) of an item
65     in a view. For more, see:
66     https://doc.qt.io/qt-5/model-view-programming.html#delegate-classes
67 
68     This class provides the logic required to paint a Layer item in the
69     :class:`napari._qt.containers.QtLayerList`.  The `QStyledItemDelegate`
70     super-class provides most of the logic (including display/editing of the
71     layer name, a visibility checkbox, and an icon for the layer type).  This
72     subclass provides additional logic for drawing the layer thumbnail, picking
73     the appropriate icon for the layer, and some additional style/UX issues.
74     """
75 
76     def paint(
77         self,
78         painter: QPainter,
79         option: QStyleOptionViewItem,
80         index: QtCore.QModelIndex,
81     ):
82         """Paint the item in the model at `index`."""
83         # update the icon based on layer type
84 
85         self.get_layer_icon(option, index)
86         # paint the standard itemView (includes name, icon, and vis. checkbox)
87         super().paint(painter, option, index)
88         # paint the thumbnail
89         self._paint_thumbnail(painter, option, index)
90 
91     def get_layer_icon(
92         self, option: QStyleOptionViewItem, index: QtCore.QModelIndex
93     ):
94         """Add the appropriate QIcon to the item based on the layer type."""
95         layer = index.data(ItemRole)
96         if layer is None:
97             return
98         if hasattr(layer, 'is_group') and layer.is_group():  # for layer trees
99             expanded = option.widget.isExpanded(index)
100             icon_name = 'folder-open' if expanded else 'folder'
101         else:
102             icon_name = f'new_{layer._type_string}'
103 
104         try:
105             icon = QColoredSVGIcon.from_resources(icon_name)
106         except ValueError:
107             return
108         # guessing theme rather than passing it through.
109         bg = option.palette.color(option.palette.ColorRole.Window).red()
110         option.icon = icon.colored(theme='dark' if bg < 128 else 'light')
111         option.decorationSize = QSize(18, 18)
112         option.decorationPosition = (
113             option.Position.Right
114         )  # put icon on the right
115         option.features |= option.ViewItemFeature.HasDecoration
116 
117     def _paint_thumbnail(self, painter, option, index):
118         """paint the layer thumbnail."""
119         # paint the thumbnail
120         # MAGICNUMBER: numbers from the margin applied in the stylesheet to
121         # QtLayerTreeView::item
122         thumb_rect = option.rect.translated(-2, 2)
123         h = index.data(Qt.ItemDataRole.SizeHintRole).height() - 4
124         thumb_rect.setWidth(h)
125         thumb_rect.setHeight(h)
126         image = index.data(ThumbnailRole)
127         painter.drawPixmap(thumb_rect, QPixmap.fromImage(image))
128 
129     def createEditor(
130         self,
131         parent: QWidget,
132         option: QStyleOptionViewItem,
133         index: QtCore.QModelIndex,
134     ) -> QWidget:
135         """User has double clicked on layer name."""
136         # necessary for geometry, otherwise editor takes up full width.
137         self.get_layer_icon(option, index)
138         editor = super().createEditor(parent, option, index)
139         # make sure editor has same alignment as the display name
140         editor.setAlignment(
141             Qt.Alignment(index.data(Qt.ItemDataRole.TextAlignmentRole))
142         )
143         return editor
144 
145     def editorEvent(
146         self,
147         event: QtCore.QEvent,
148         model: QtCore.QAbstractItemModel,
149         option: QStyleOptionViewItem,
150         index: QtCore.QModelIndex,
151     ) -> bool:
152         """Called when an event has occured in the editor.
153 
154         This can be used to customize how the delegate handles mouse/key events
155         """
156         if (
157             event.type() == QMouseEvent.MouseButtonRelease
158             and event.button() == Qt.MouseButton.RightButton
159         ):
160             pnt = (
161                 event.globalPosition().toPoint()
162                 if hasattr(event, "globalPosition")
163                 else event.globalPos()
164             )
165 
166             self.show_context_menu(index, model, pnt, option.widget)
167 
168         # if the user clicks quickly on the visibility checkbox, we *don't*
169         # want it to be interpreted as a double-click.  We want the visibilty
170         # to simply be toggled.
171         if event.type() == QMouseEvent.MouseButtonDblClick:
172             self.initStyleOption(option, index)
173             style = option.widget.style()
174             check_rect = style.subElementRect(
175                 style.SubElement.SE_ItemViewItemCheckIndicator,
176                 option,
177                 option.widget,
178             )
179             if check_rect.contains(event.pos()):
180                 cur_state = index.data(Qt.ItemDataRole.CheckStateRole)
181                 if model.flags(index) & Qt.ItemFlag.ItemIsUserTristate:
182                     state = Qt.CheckState((cur_state + 1) % 3)
183                 else:
184                     state = (
185                         Qt.CheckState.Unchecked
186                         if cur_state
187                         else Qt.CheckState.Checked
188                     )
189                 return model.setData(
190                     index, state, Qt.ItemDataRole.CheckStateRole
191                 )
192         # refer all other events to the QStyledItemDelegate
193         return super().editorEvent(event, model, option, index)
194 
195     def show_context_menu(self, index, model, pos: QPoint, parent):
196         """Show the layerlist context menu.
197         To add a new item to the menu, update the _LAYER_ACTIONS dict.
198         """
199         if not hasattr(self, '_context_menu'):
200             self._context_menu = build_qmodel_menu(
201                 MenuId.LAYERLIST_CONTEXT, parent=parent
202             )
203 
204         layer_list: LayerList = model.sourceModel()._root
205         self._context_menu.update_from_context(get_context(layer_list))
206         self._context_menu.exec_(pos)
207
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/napari/_qt/containers/_layer_delegate.py b/napari/_qt/containers/_layer_delegate.py
--- a/napari/_qt/containers/_layer_delegate.py
+++ b/napari/_qt/containers/_layer_delegate.py
@@ -138,7 +138,7 @@
         editor = super().createEditor(parent, option, index)
         # make sure editor has same alignment as the display name
         editor.setAlignment(
-            Qt.Alignment(index.data(Qt.ItemDataRole.TextAlignmentRole))
+            Qt.AlignmentFlag(index.data(Qt.ItemDataRole.TextAlignmentRole))
         )
         return editor

{"golden_diff": "diff --git a/napari/_qt/containers/_layer_delegate.py b/napari/_qt/containers/_layer_delegate.py\n--- a/napari/_qt/containers/_layer_delegate.py\n+++ b/napari/_qt/containers/_layer_delegate.py\n@@ -138,7 +138,7 @@\n         editor = super().createEditor(parent, option, index)\n         # make sure editor has same alignment as the display name\n         editor.setAlignment(\n-            Qt.Alignment(index.data(Qt.ItemDataRole.TextAlignmentRole))\n+            Qt.AlignmentFlag(index.data(Qt.ItemDataRole.TextAlignmentRole))\n         )\n         return editor\n", "issue": "[Qt6] AttributeError when renaming a layer\n## \ud83d\udc1b Bug\r\n\r\nThis seems to be yet another small Qt6 issue related to enum name changes.\r\n\r\n## To Reproduce\r\n\r\nSteps to reproduce the behavior:\r\n\r\n1. Launch napari from a Qt6 environment\r\n2. Open a file or otherwise create a new layer\r\n3. Double click the layer to rename it, triggering the exception\r\n\r\n```\r\n---------------------------------------------------------------------------\r\nAttributeError                            Traceback (most recent call last)\r\nFile ~/src/napari/napari/_qt/containers/_layer_delegate.py:141, in LayerDelegate.createEditor(self=<napari._qt.containers._layer_delegate.LayerDelegate object>, parent=<PyQt6.QtWidgets.QWidget object>, option=<PyQt6.QtWidgets.QStyleOptionViewItem object>, index=<PyQt6.QtCore.QModelIndex object>)\r\n    138 editor = super().createEditor(parent, option, index)\r\n    139 # make sure editor has same alignment as the display name\r\n    140 editor.setAlignment(\r\n--> 141     Qt.Alignment(index.data(Qt.ItemDataRole.TextAlignmentRole))\r\n        editor = <PyQt6.QtWidgets.QLineEdit object at 0x2aaa3e4d0>\r\n        index = <PyQt6.QtCore.QModelIndex object at 0x16b74ee30>\r\n        Qt = <class 'PyQt6.QtCore.Qt'>\r\n        Qt.ItemDataRole.TextAlignmentRole = <ItemDataRole.TextAlignmentRole: 7>\r\n    142 )\r\n    143 return editor\r\n\r\nAttributeError: type object 'Qt' has no attribute 'Alignment'\r\n```\r\n\r\n## Expected behavior\r\n\r\nDouble-clicking the layer should allow editing the layer name and not raise an exception.\r\n\r\n## Environment\r\n\r\nnapari: 0.5.0a2.dev129+g0dfb37b47.d20230518\r\nPlatform: macOS-13.3.1-arm64-arm-64bit\r\nSystem: MacOS 13.3.1\r\nPython: 3.10.9 (main, Feb 3 2023, 15:40:08) [Clang 14.0.0 (clang-1400.0.29.202)]\r\nQt: 6.5.0\r\nPyQt6: \r\nNumPy: 1.24.1\r\nSciPy: 1.10.0\r\nDask: 2023.1.1\r\nVisPy: 0.12.3.dev45+dirty\r\nmagicgui: 0.6.1\r\nsuperqt: unknown\r\nin-n-out: 0.1.6\r\napp-model: 0.1.1.dev3+gdf48c9d\r\nnpe2: 0.6.2\r\n\r\nOpenGL:\r\n- GL version: 2.1 Metal - 83.1\r\n- MAX_TEXTURE_SIZE: 16384\r\n\r\nScreens:\r\n- screen 1: resolution 2560x1440, scale 1.0\r\n\r\nSettings path:\r\n- /Users/aandersoniii/Library/Application Support/napari/venv_640f7def1935afdf07a142187e645430c6d70fe6/settings.yaml\n", "before_files": [{"content": "\"\"\"\nGeneral rendering flow:\n\n1. The List/Tree view needs to display or edit an index in the model...\n2. It gets the ``itemDelegate``\n    a. A custom delegate can be set with ``setItemDelegate``\n    b. ``QStyledItemDelegate`` is the default delegate for all Qt item views,\n       and is installed upon them when they are created.\n3. ``itemDelegate.paint`` is called on the index being displayed\n4. Each index in the model has various data elements (i.e. name, image, etc..),\n   each of which has a \"data role\".  A model should return the appropriate data\n   for each role by reimplementing ``QAbstractItemModel.data``.\n    a. `QStyledItemDelegate` implements display and editing for the most common\n       datatypes expected by users, including booleans, integers, and strings.\n    b. If the delegate does not support painting of the data types you need or\n       you want to customize the drawing of items, you need to subclass\n       ``QStyledItemDelegate``, and reimplement ``paint()`` and possibly\n       ``sizeHint()``.\n    c. When reimplementing ``paint()``, one typically handles the datatypes\n       they would like to draw and uses the superclass implementation for other\n       types.\n5. The default implementation of ``QStyledItemDelegate.paint`` paints the item\n   using the view's ``QStyle`` (which is, by default, an OS specific style...\n   but see ``QCommonStyle`` for a generic implementation)\n    a. It is also possible to override the view's style, using either a\n    subclass of ``QCommonStyle``, for a platform-independent look and feel, or\n    ``QProxyStyle``, which let's you override only certain stylistic elements\n    on any platform, falling back to the system default otherwise.\n    b. ``QStyle`` paints various elements using methods like ``drawPrimitive``\n       and ``drawControl``.  These can be overridden for very fine control.\n6. It is hard to use stylesheets with custom ``QStyles``... but it's possible\n   to style sub-controls in ``QAbstractItemView`` (such as ``QTreeView``):\n   https://doc.qt.io/qt-5/stylesheet-reference.html#list-of-sub-controls\n\n\"\"\"\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom qtpy.QtCore import QPoint, QSize, Qt\nfrom qtpy.QtGui import QMouseEvent, QPixmap\nfrom qtpy.QtWidgets import QStyledItemDelegate\n\nfrom napari._app_model.constants import MenuId\nfrom napari._app_model.context import get_context\nfrom napari._qt._qapp_model import build_qmodel_menu\nfrom napari._qt.containers._base_item_model import ItemRole\nfrom napari._qt.containers.qt_layer_model import ThumbnailRole\nfrom napari._qt.qt_resources import QColoredSVGIcon\n\nif TYPE_CHECKING:\n    from qtpy import QtCore\n    from qtpy.QtGui import QPainter\n    from qtpy.QtWidgets import QStyleOptionViewItem, QWidget\n\n    from napari.components.layerlist import LayerList\n\n\nclass LayerDelegate(QStyledItemDelegate):\n    \"\"\"A QItemDelegate specialized for painting Layer objects.\n\n    In Qt's `Model/View architecture\n    <https://doc.qt.io/qt-5/model-view-programming.html>`_. A *delegate* is an\n    object that controls the visual rendering (and editing widgets) of an item\n    in a view. For more, see:\n    https://doc.qt.io/qt-5/model-view-programming.html#delegate-classes\n\n    This class provides the logic required to paint a Layer item in the\n    :class:`napari._qt.containers.QtLayerList`.  The `QStyledItemDelegate`\n    super-class provides most of the logic (including display/editing of the\n    layer name, a visibility checkbox, and an icon for the layer type).  This\n    subclass provides additional logic for drawing the layer thumbnail, picking\n    the appropriate icon for the layer, and some additional style/UX issues.\n    \"\"\"\n\n    def paint(\n        self,\n        painter: QPainter,\n        option: QStyleOptionViewItem,\n        index: QtCore.QModelIndex,\n    ):\n        \"\"\"Paint the item in the model at `index`.\"\"\"\n        # update the icon based on layer type\n\n        self.get_layer_icon(option, index)\n        # paint the standard itemView (includes name, icon, and vis. checkbox)\n        super().paint(painter, option, index)\n        # paint the thumbnail\n        self._paint_thumbnail(painter, option, index)\n\n    def get_layer_icon(\n        self, option: QStyleOptionViewItem, index: QtCore.QModelIndex\n    ):\n        \"\"\"Add the appropriate QIcon to the item based on the layer type.\"\"\"\n        layer = index.data(ItemRole)\n        if layer is None:\n            return\n        if hasattr(layer, 'is_group') and layer.is_group():  # for layer trees\n            expanded = option.widget.isExpanded(index)\n            icon_name = 'folder-open' if expanded else 'folder'\n        else:\n            icon_name = f'new_{layer._type_string}'\n\n        try:\n            icon = QColoredSVGIcon.from_resources(icon_name)\n        except ValueError:\n            return\n        # guessing theme rather than passing it through.\n        bg = option.palette.color(option.palette.ColorRole.Window).red()\n        option.icon = icon.colored(theme='dark' if bg < 128 else 'light')\n        option.decorationSize = QSize(18, 18)\n        option.decorationPosition = (\n            option.Position.Right\n        )  # put icon on the right\n        option.features |= option.ViewItemFeature.HasDecoration\n\n    def _paint_thumbnail(self, painter, option, index):\n        \"\"\"paint the layer thumbnail.\"\"\"\n        # paint the thumbnail\n        # MAGICNUMBER: numbers from the margin applied in the stylesheet to\n        # QtLayerTreeView::item\n        thumb_rect = option.rect.translated(-2, 2)\n        h = index.data(Qt.ItemDataRole.SizeHintRole).height() - 4\n        thumb_rect.setWidth(h)\n        thumb_rect.setHeight(h)\n        image = index.data(ThumbnailRole)\n        painter.drawPixmap(thumb_rect, QPixmap.fromImage(image))\n\n    def createEditor(\n        self,\n        parent: QWidget,\n        option: QStyleOptionViewItem,\n        index: QtCore.QModelIndex,\n    ) -> QWidget:\n        \"\"\"User has double clicked on layer name.\"\"\"\n        # necessary for geometry, otherwise editor takes up full width.\n        self.get_layer_icon(option, index)\n        editor = super().createEditor(parent, option, index)\n        # make sure editor has same alignment as the display name\n        editor.setAlignment(\n            Qt.Alignment(index.data(Qt.ItemDataRole.TextAlignmentRole))\n        )\n        return editor\n\n    def editorEvent(\n        self,\n        event: QtCore.QEvent,\n        model: QtCore.QAbstractItemModel,\n        option: QStyleOptionViewItem,\n        index: QtCore.QModelIndex,\n    ) -> bool:\n        \"\"\"Called when an event has occured in the editor.\n\n        This can be used to customize how the delegate handles mouse/key events\n        \"\"\"\n        if (\n            event.type() == QMouseEvent.MouseButtonRelease\n            and event.button() == Qt.MouseButton.RightButton\n        ):\n            pnt = (\n                event.globalPosition().toPoint()\n                if hasattr(event, \"globalPosition\")\n                else event.globalPos()\n            )\n\n            self.show_context_menu(index, model, pnt, option.widget)\n\n        # if the user clicks quickly on the visibility checkbox, we *don't*\n        # want it to be interpreted as a double-click.  We want the visibilty\n        # to simply be toggled.\n        if event.type() == QMouseEvent.MouseButtonDblClick:\n            self.initStyleOption(option, index)\n            style = option.widget.style()\n            check_rect = style.subElementRect(\n                style.SubElement.SE_ItemViewItemCheckIndicator,\n                option,\n                option.widget,\n            )\n            if check_rect.contains(event.pos()):\n                cur_state = index.data(Qt.ItemDataRole.CheckStateRole)\n                if model.flags(index) & Qt.ItemFlag.ItemIsUserTristate:\n                    state = Qt.CheckState((cur_state + 1) % 3)\n                else:\n                    state = (\n                        Qt.CheckState.Unchecked\n                        if cur_state\n                        else Qt.CheckState.Checked\n                    )\n                return model.setData(\n                    index, state, Qt.ItemDataRole.CheckStateRole\n                )\n        # refer all other events to the QStyledItemDelegate\n        return super().editorEvent(event, model, option, index)\n\n    def show_context_menu(self, index, model, pos: QPoint, parent):\n        \"\"\"Show the layerlist context menu.\n        To add a new item to the menu, update the _LAYER_ACTIONS dict.\n        \"\"\"\n        if not hasattr(self, '_context_menu'):\n            self._context_menu = build_qmodel_menu(\n                MenuId.LAYERLIST_CONTEXT, parent=parent\n            )\n\n        layer_list: LayerList = model.sourceModel()._root\n        self._context_menu.update_from_context(get_context(layer_list))\n        self._context_menu.exec_(pos)\n", "path": "napari/_qt/containers/_layer_delegate.py"}], "after_files": [{"content": "\"\"\"\nGeneral rendering flow:\n\n1. The List/Tree view needs to display or edit an index in the model...\n2. It gets the ``itemDelegate``\n    a. A custom delegate can be set with ``setItemDelegate``\n    b. ``QStyledItemDelegate`` is the default delegate for all Qt item views,\n       and is installed upon them when they are created.\n3. ``itemDelegate.paint`` is called on the index being displayed\n4. Each index in the model has various data elements (i.e. name, image, etc..),\n   each of which has a \"data role\".  A model should return the appropriate data\n   for each role by reimplementing ``QAbstractItemModel.data``.\n    a. `QStyledItemDelegate` implements display and editing for the most common\n       datatypes expected by users, including booleans, integers, and strings.\n    b. If the delegate does not support painting of the data types you need or\n       you want to customize the drawing of items, you need to subclass\n       ``QStyledItemDelegate``, and reimplement ``paint()`` and possibly\n       ``sizeHint()``.\n    c. When reimplementing ``paint()``, one typically handles the datatypes\n       they would like to draw and uses the superclass implementation for other\n       types.\n5. The default implementation of ``QStyledItemDelegate.paint`` paints the item\n   using the view's ``QStyle`` (which is, by default, an OS specific style...\n   but see ``QCommonStyle`` for a generic implementation)\n    a. It is also possible to override the view's style, using either a\n    subclass of ``QCommonStyle``, for a platform-independent look and feel, or\n    ``QProxyStyle``, which let's you override only certain stylistic elements\n    on any platform, falling back to the system default otherwise.\n    b. ``QStyle`` paints various elements using methods like ``drawPrimitive``\n       and ``drawControl``.  These can be overridden for very fine control.\n6. It is hard to use stylesheets with custom ``QStyles``... but it's possible\n   to style sub-controls in ``QAbstractItemView`` (such as ``QTreeView``):\n   https://doc.qt.io/qt-5/stylesheet-reference.html#list-of-sub-controls\n\n\"\"\"\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom qtpy.QtCore import QPoint, QSize, Qt\nfrom qtpy.QtGui import QMouseEvent, QPixmap\nfrom qtpy.QtWidgets import QStyledItemDelegate\n\nfrom napari._app_model.constants import MenuId\nfrom napari._app_model.context import get_context\nfrom napari._qt._qapp_model import build_qmodel_menu\nfrom napari._qt.containers._base_item_model import ItemRole\nfrom napari._qt.containers.qt_layer_model import ThumbnailRole\nfrom napari._qt.qt_resources import QColoredSVGIcon\n\nif TYPE_CHECKING:\n    from qtpy import QtCore\n    from qtpy.QtGui import QPainter\n    from qtpy.QtWidgets import QStyleOptionViewItem, QWidget\n\n    from napari.components.layerlist import LayerList\n\n\nclass LayerDelegate(QStyledItemDelegate):\n    \"\"\"A QItemDelegate specialized for painting Layer objects.\n\n    In Qt's `Model/View architecture\n    <https://doc.qt.io/qt-5/model-view-programming.html>`_. A *delegate* is an\n    object that controls the visual rendering (and editing widgets) of an item\n    in a view. For more, see:\n    https://doc.qt.io/qt-5/model-view-programming.html#delegate-classes\n\n    This class provides the logic required to paint a Layer item in the\n    :class:`napari._qt.containers.QtLayerList`.  The `QStyledItemDelegate`\n    super-class provides most of the logic (including display/editing of the\n    layer name, a visibility checkbox, and an icon for the layer type).  This\n    subclass provides additional logic for drawing the layer thumbnail, picking\n    the appropriate icon for the layer, and some additional style/UX issues.\n    \"\"\"\n\n    def paint(\n        self,\n        painter: QPainter,\n        option: QStyleOptionViewItem,\n        index: QtCore.QModelIndex,\n    ):\n        \"\"\"Paint the item in the model at `index`.\"\"\"\n        # update the icon based on layer type\n\n        self.get_layer_icon(option, index)\n        # paint the standard itemView (includes name, icon, and vis. checkbox)\n        super().paint(painter, option, index)\n        # paint the thumbnail\n        self._paint_thumbnail(painter, option, index)\n\n    def get_layer_icon(\n        self, option: QStyleOptionViewItem, index: QtCore.QModelIndex\n    ):\n        \"\"\"Add the appropriate QIcon to the item based on the layer type.\"\"\"\n        layer = index.data(ItemRole)\n        if layer is None:\n            return\n        if hasattr(layer, 'is_group') and layer.is_group():  # for layer trees\n            expanded = option.widget.isExpanded(index)\n            icon_name = 'folder-open' if expanded else 'folder'\n        else:\n            icon_name = f'new_{layer._type_string}'\n\n        try:\n            icon = QColoredSVGIcon.from_resources(icon_name)\n        except ValueError:\n            return\n        # guessing theme rather than passing it through.\n        bg = option.palette.color(option.palette.ColorRole.Window).red()\n        option.icon = icon.colored(theme='dark' if bg < 128 else 'light')\n        option.decorationSize = QSize(18, 18)\n        option.decorationPosition = (\n            option.Position.Right\n        )  # put icon on the right\n        option.features |= option.ViewItemFeature.HasDecoration\n\n    def _paint_thumbnail(self, painter, option, index):\n        \"\"\"paint the layer thumbnail.\"\"\"\n        # paint the thumbnail\n        # MAGICNUMBER: numbers from the margin applied in the stylesheet to\n        # QtLayerTreeView::item\n        thumb_rect = option.rect.translated(-2, 2)\n        h = index.data(Qt.ItemDataRole.SizeHintRole).height() - 4\n        thumb_rect.setWidth(h)\n        thumb_rect.setHeight(h)\n        image = index.data(ThumbnailRole)\n        painter.drawPixmap(thumb_rect, QPixmap.fromImage(image))\n\n    def createEditor(\n        self,\n        parent: QWidget,\n        option: QStyleOptionViewItem,\n        index: QtCore.QModelIndex,\n    ) -> QWidget:\n        \"\"\"User has double clicked on layer name.\"\"\"\n        # necessary for geometry, otherwise editor takes up full width.\n        self.get_layer_icon(option, index)\n        editor = super().createEditor(parent, option, index)\n        # make sure editor has same alignment as the display name\n        editor.setAlignment(\n            Qt.AlignmentFlag(index.data(Qt.ItemDataRole.TextAlignmentRole))\n        )\n        return editor\n\n    def editorEvent(\n        self,\n        event: QtCore.QEvent,\n        model: QtCore.QAbstractItemModel,\n        option: QStyleOptionViewItem,\n        index: QtCore.QModelIndex,\n    ) -> bool:\n        \"\"\"Called when an event has occured in the editor.\n\n        This can be used to customize how the delegate handles mouse/key events\n        \"\"\"\n        if (\n            event.type() == QMouseEvent.MouseButtonRelease\n            and event.button() == Qt.MouseButton.RightButton\n        ):\n            pnt = (\n                event.globalPosition().toPoint()\n                if hasattr(event, \"globalPosition\")\n                else event.globalPos()\n            )\n\n            self.show_context_menu(index, model, pnt, option.widget)\n\n        # if the user clicks quickly on the visibility checkbox, we *don't*\n        # want it to be interpreted as a double-click.  We want the visibilty\n        # to simply be toggled.\n        if event.type() == QMouseEvent.MouseButtonDblClick:\n            self.initStyleOption(option, index)\n            style = option.widget.style()\n            check_rect = style.subElementRect(\n                style.SubElement.SE_ItemViewItemCheckIndicator,\n                option,\n                option.widget,\n            )\n            if check_rect.contains(event.pos()):\n                cur_state = index.data(Qt.ItemDataRole.CheckStateRole)\n                if model.flags(index) & Qt.ItemFlag.ItemIsUserTristate:\n                    state = Qt.CheckState((cur_state + 1) % 3)\n                else:\n                    state = (\n                        Qt.CheckState.Unchecked\n                        if cur_state\n                        else Qt.CheckState.Checked\n                    )\n                return model.setData(\n                    index, state, Qt.ItemDataRole.CheckStateRole\n                )\n        # refer all other events to the QStyledItemDelegate\n        return super().editorEvent(event, model, option, index)\n\n    def show_context_menu(self, index, model, pos: QPoint, parent):\n        \"\"\"Show the layerlist context menu.\n        To add a new item to the menu, update the _LAYER_ACTIONS dict.\n        \"\"\"\n        if not hasattr(self, '_context_menu'):\n            self._context_menu = build_qmodel_menu(\n                MenuId.LAYERLIST_CONTEXT, parent=parent\n            )\n\n        layer_list: LayerList = model.sourceModel()._root\n        self._context_menu.update_from_context(get_context(layer_list))\n        self._context_menu.exec_(pos)\n", "path": "napari/_qt/containers/_layer_delegate.py"}]}