+6 votes

I have a Tree node that I add with an addon to the Godot 3 editor:

enter image description here

How would I go about adding drag and drop to it?

in Engine by (21 points)

1 Answer

+4 votes
Best answer

Figured how to do so myself so posting a snippet:

extends Tree

signal moved(item, to_item, shift)

func get_drag_data(position): # begin drag
    set_drop_mode_flags(DROP_MODE_INBETWEEN | DROP_MODE_ON_ITEM)

    var preview = Label.new()
    preview.text = get_selected().get_text(0)
    set_drag_preview(preview) # not necessary

    return get_selected() # TreeItem

func can_drop_data(position, data):
    return data is TreeItem # you shall not pass!

func drop_data(position, item): # end drag
    var to_item = get_item_at_position(position)
    var shift = get_drop_section_at_position(position)
    # shift == 0 if dropping on item, -1, +1 if in between

    emit_signal('moved', item, to_item, shift)

From there you should update your tree according to requested moved signal from data which must determine the order of items (for this I just clear all items and repopulate them). Note that the extended Tree class should likely operate in tool mode if writing plugins for this to work. You could embed your data in TreeItems with set_metadata per column or set_meta per item for dragging and other purposes.

by (1,356 points)
selected by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.