Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | senshellshark |
Have a Tree node that I populate using the function add_new_item
. I can add and edit these Tree Items just fine but I want to be able to reorder them and re-parent them with drag and drop actions. When dragging and item I get outlines as I would expect, showing where the item will go, either under, above or on top of another item. When I start to drag though my cursor becomes an X. I guess the action I’m attempting is somehow invalid? How do I validate my drag and drop motions so my script can do what it needs to do?
Here is my current script:
extends Tree
var root = TreeItem
enum {BEFORE = -1, ON = 0, AFTER = 1}
signal moved(item, to_item, shift)
func _ready():
root = create_item()
func add_new_item(item_name: String):
var selected = get_selected()
var item = create_item(selected) if selected else create_item(root)
item.set_text(0, item_name)
item.set_editable(0, true)
func _get_drag_data(_item_position):
set_drop_mode_flags(DROP_MODE_INBETWEEN | DROP_MODE_ON_ITEM)
var selected = get_selected()
if not selected:
return
var preview = Label.new()
preview.text = selected.get_text(0)
set_drag_preview(preview)
return selected
func can_drop_data(_item_position, data):
return data is TreeItem
func drop_data(item_position, item):
var to_item = get_item_at_position(item_position)
var shift = get_drop_section_at_position(item_position)
var success = move_item(item, to_item, shift)
if not success:
return
emit_signal('moved', item, to_item, shift)
func move_item(item: TreeItem, to_item: TreeItem, shift: int):
if item == to_item:
return
match(shift):
BEFORE:
item.move_before(to_item)
ON:
var dummy = create_item(to_item)
item.move_after(dummy)
to_item.remove_child(dummy)
AFTER:
item.move_after(to_item)
return true
How it looks when I try to drag and drop an item: