Flet 0.28.xでD&Dによる入れ子構造リストを作成します。以下のような機能を実装します:
import flet as ft
from typing import List, Dict, Optional
import uuid
class NestedListItem:
def __init__(self, title: str, parent_id: Optional[str] = None):
self.id = str(uuid.uuid4())
self.title = title
self.parent_id = parent_id
self.children: List[str] = []
self.expanded = True
class NestedDragDropList:
def __init__(self):
self.items: Dict[str, NestedListItem] = {}
self.root_items: List[str] = []
self.drag_data = None
def add_item(self, title: str, parent_id: Optional[str] = None) -> str:
item = NestedListItem(title, parent_id)
self.items[item.id] = item
if parent_id:
self.items[parent_id].children.append(item.id)
else:
self.root_items.append(item.id)
return item.id
def move_item(self, item_id: str, new_parent_id: Optional[str], position: int = -1):
if item_id not in self.items:
return
item = self.items[item_id]
old_parent_id = item.parent_id
# 古い親から削除
if old_parent_id:
self.items[old_parent_id].children.remove(item_id)
else:
self.root_items.remove(item_id)
# 新しい親に追加
item.parent_id = new_parent_id
if new_parent_id:
if position == -1:
self.items[new_parent_id].children.append(item_id)
else:
self.items[new_parent_id].children.insert(position, item_id)
else:
if position == -1:
self.root_items.append(item_id)
else:
self.root_items.insert(position, item_id)
def get_level(self, item_id: str) -> int:
level = 0
current_id = item_id
while current_id and self.items.get(current_id):
parent_id = self.items[current_id].parent_id
if parent_id:
level += 1
current_id = parent_id
else:
break
return level
def main(page: ft.Page):
page.title = "入れ子構造D&Dリスト"
page.theme_mode = ft.ThemeMode.LIGHT
nested_list = NestedDragDropList()
# サンプルデータ
root1 = nested_list.add_item("プロジェクト A")
child1 = nested_list.add_item("タスク 1", root1)
child2 = nested_list.add_item("タスク 2", root1)
grandchild1 = nested_list.add_item("サブタスク 1", child1)
root2 = nested_list.add_item("プロジェクト B")
child3 = nested_list.add_item("タスク 3", root2)
def create_list_item(item_id: str) -> ft.Control:
item = nested_list.items[item_id]
level = nested_list.get_level(item_id)
# インデントの計算
indent = level * 20
# 子要素があるかどうか
has_children = len(item.children) > 0
# 展開/折りたたみアイコン
expand_icon = ft.IconButton(
icon=ft.Icons.EXPAND_MORE if item.expanded else ft.Icons.CHEVRON_RIGHT,
icon_size=16,
on_click=lambda e, id=item_id: toggle_expand(id)
) if has_children else ft.Container(width=32)
# ドラッグ可能なアイテム
draggable_content = ft.Draggable(
group="list_items",
content=ft.Container(
content=ft.Row([
expand_icon,
ft.Icon(ft.Icons.DRAG_INDICATOR, size=16, color=ft.Colors.GREY_400),
ft.Text(item.title, size=14),
], spacing=5),
padding=ft.padding.only(left=indent, top=5, bottom=5, right=10),
bgcolor=ft.Colors.WHITE,
border=ft.border.all(1, ft.Colors.GREY_300),
border_radius=4,
margin=ft.margin.only(bottom=2)
),
data=item_id
)
# ドロップターゲット
drop_target = ft.DragTarget(
group="list_items",
content=draggable_content,
on_accept=lambda e, target_id=item_id: handle_drop(e, target_id)
)
return drop_target
def toggle_expand(item_id: str):
item = nested_list.items[item_id]
item.expanded = not item.expanded
update_list()
def handle_drop(e: ft.DragTargetAcceptEvent, target_id: str):
dragged_id = e.src_id
if dragged_id == target_id:
return
# 循環参照チェック
if is_descendant(target_id, dragged_id):
show_error("親要素を子要素の中に移動することはできません")
return
# アイテムを新しい親の下に移動
nested_list.move_item(dragged_id, target_id)
update_list()
def is_descendant(ancestor_id: str, descendant_id: str) -> bool:
"""descendant_idがancestor_idの子孫かどうかチェック"""
current_id = descendant_id
while current_id:
if current_id == ancestor_id:
return True
current_id = nested_list.items.get(current_id, {}).parent_id
return False
def show_error(message: str):
page.show_snack_bar(ft.SnackBar(content=ft.Text(message)))
def build_tree_view(item_ids: List[str]) -> List[ft.Control]:
controls = []
for item_id in item_ids:
item = nested_list.items[item_id]
controls.append(create_list_item(item_id))
# 子要素を再帰的に追加
if item.expanded and item.children:
child_controls = build_tree_view(item.children)
controls.extend(child_controls)
return controls
def update_list():
list_view.controls.clear()
tree_controls = build_tree_view(nested_list.root_items)
list_view.controls.extend(tree_controls)
# ルートレベルのドロップターゲット
root_drop_target = ft.DragTarget(
group="list_items",
content=ft.Container(
content=ft.Text("ここにドロップしてルートレベルに移動",
color=ft.Colors.GREY_500, size=12),
height=40,
alignment=ft.alignment.center,
bgcolor=ft.Colors.GREY_100,
border=ft.border.all(1, ft.Colors.GREY_300),
border_radius=4,
margin=ft.margin.only(top=10)
),
on_accept=lambda e: handle_root_drop(e)
)
list_view.controls.append(root_drop_target)
page.update()
def handle_root_drop(e: ft.DragTargetAcceptEvent):
dragged_id = e.src_id
nested_list.move_item(dragged_id, None)
update_list()
def add_new_item(e):
title = new_item_field.value.strip()
if title:
nested_list.add_item(title)
new_item_field.value = ""
update_list()
# UI要素
new_item_field = ft.TextField(
label="新しいアイテム",
expand=True,
on_submit=add_new_item
)
add_button = ft.ElevatedButton(
"追加",
on_click=add_new_item,
icon=ft.Icons.ADD
)
list_view = ft.Column(
spacing=0,
scroll=ft.ScrollMode.AUTO
)
# レイアウト
page.add(
ft.Container(
content=ft.Column([
ft.Row([
new_item_field,
add_button
], spacing=10),
ft.Divider(),
ft.Container(
content=list_view,
height=500,
border=ft.border.all(1, ft.Colors.GREY_300),
border_radius=8,
padding=10
),
ft.Text(
"操作方法:\n• ドラッグ&ドロップでアイテムを移動\n• 他のアイテムにドロップすると子要素になります\n• 下部の灰色エリアにドロップするとルートレベルに移動",
size=12,
color=ft.Colors.GREY_600
)
], spacing=10),
padding=20
)
)
# 初期表示
update_list()
if __name__ == "__main__":
ft.app(target=main)
この実装の特徴:
主な機能
- ドラッグ&ドロップによる階層移動
- 入れ子構造の視覚的表現(インデント)
- 展開/折りたたみ機能
- 新しいアイテムの追加
- 循環参照の防止
操作方法
- アイテムをドラッグして他のアイテムにドロップ → 子要素になる
- 下部の灰色エリアにドロップ → ルートレベルに移動
- 親要素のアイコンクリック → 子要素の表示/非表示切り替え
技術的なポイント
flet.Draggableとflet.DragTargetでD&D実装
flet.Iconsとflet.Colorsを使用(0.28.x対応)
- 再帰的な構造でツリー表示
- データ構造とUI表示の分離
この実装により、直感的な操作で入れ子構造のリストを管理できます。