Mouse 'grab and drag'? #2752
-
Perhaps this is just beyond my coding skills, but I am really struggling to understand how to add mouse 'grab and drag' functionality in Textual, like you see with the scrollbars. I've read through the Mouse Input guide and the repo for several widgets, but I still don't understand how something like the scrollbar actually works. If anyone could provide just a very simple code example, I would be very grateful! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Here's an example of dragging virtual objects around within a widget, for a simulated aquarium: def entity_at(offset: Offset, entities: list[Entity]) -> Entity | None:
for entity in entities:
if entity.x <= offset.x < entity.x + entity.width and entity.y <= offset.y < entity.y + entity.height:
return entity
return None
class Tank(Widget):
dragging: var[Entity | None] = var[Entity | None](None)
drag_offset: var[Offset | None] = var[Offset | None](None)
def on_mouse_down(self, event: events.MouseDown) -> None:
self.capture_mouse()
self.dragging = entity_at(event.offset, Entity.instances)
if self.dragging is not None:
self.drag_offset = event.offset - Offset(self.dragging.x, self.dragging.y)
def on_mouse_up(self, event: events.MouseUp) -> None:
self.release_mouse()
self.dragging = None
self.drag_offset = None
def on_mouse_move(self, event: events.MouseMove) -> None:
if event.button != 1:
return
if self.dragging is not None:
self.dragging.x = event.offset.x - self.drag_offset.x
self.dragging.y = event.offset.y - self.drag_offset.y This excerpt isn't runnable directly, but the full code is pretty down to earth (other than the meta programming in the Entity class that I added for my own learning purposes.) Note that this code is for dragging game objects (entities) which are not widgets. If you want to drag widgets themselves around, I've implemented draggable windows for another project, so I could definitely help you out. Let me know if this is what you're looking for and I could distill this into an example for you. (Unlike the aquarium project, the code is not clean and simple, as it stands.) |
Beta Was this translation helpful? Give feedback.
Here's an example of dragging virtual objects around within a widget, for a simulated aquarium: