File: q_node_tree.py

package info (click to toggle)
napari 0.6.6-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 12,036 kB
  • sloc: python: 112,264; xml: 72; makefile: 44; sh: 5
file content (79 lines) | stat: -rw-r--r-- 2,046 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""Example of using low-level QtNodeTreeView with Node and Group

:class:`napari.utils.tree.Node` is a class that may be used as a mixin that
allows an object to be a member of a "tree".

:class:`napari.utils.tree.Group` is a (nestable) mutable sequence of Nodes, and
is also itself a Node (this is the "composite" pattern):
https://refactoring.guru/design-patterns/composite/python/example

These two classes may be used to create tree-like data structures that behave
like pure python lists of lists.

This examples shows that :class:`napari._qt.containers.QtNodeTreeView`
is capable of providing a basic GUI for any tree structure based on
`napari.utils.tree.Group`.
"""
import napari
from napari._qt.containers import QtNodeTreeView
from napari.qt import get_qapp
from napari.utils.tree import Group, Node

get_qapp()

# create a group of nodes.
root = Group(
    [
        Node(name='6'),
        Group(
            [
                Node(name='1'),
                Group([Node(name='2'), Node(name='3')], name='g2'),
                Node(name='4'),
                Node(name='5'),
                Node(name='tip'),
            ],
            name='g1',
        ),
        Node(name='7'),
        Node(name='8'),
        Node(name='9'),
    ],
    name='root',
)
# create Qt view onto the Group
view = QtNodeTreeView(root)
# show the view
view.show()


# pretty __str__ makes nested tree structure more interpretable
print(root)
# root
#   ├──6
#   ├──g1
#   │  ├──1
#   │  ├──g2
#   │  │  ├──2
#   │  │  └──3
#   │  ├──4
#   │  ├──5
#   │  └──tip
#   ├──7
#   ├──8
#   └──9


# spy on events
root.events.reordered.connect(lambda e: print('reordered to: ', e.value))
root.selection.events.changed.connect(
    lambda e: print(
        f'selection changed.  added: {e.added}, removed: {e.removed}'
    )
)
root.selection.events._current.connect(
    lambda e: print(f'current item changed to: {e.value}')
)

if __name__ == '__main__':
    napari.run()