Search code examples
gofyne

Make Fyne popup menu appear at mouse position


I'm stuck at getting the position of the mouse. I want to show the Fyne popup menu at the position of the mouse but can't figure it out.

Here's how I use the popup:

menuItem1 := fyne.NewMenuItem("A", nil)
menuItem2 := fyne.NewMenuItem("B", nil)
menuItem3 := fyne.NewMenuItem("C", nil)
menu := fyne.NewMenu("File", menuItem1, menuItem2, menuItem3)

popUpMenu := widget.NewPopUpMenu(menu, window.Canvas())

popUpMenu.ShowAtPosition(*Expect mouse position here*)
popUpMenu.Show()

I would expect to put in the mouse position as a Fyne Position at the mentioned position. But I don't know where I can get the mouse/cursor position from.

This way the popup is always stuck to the top left of the app.


Solution

  • The PointEvent is passed into the methods that implement interfaces to do with interaction. Button OnTapped hides these details as they are not normally needed.

    As suggested in some comments, you should extend the widget you want to respond to this like the button in fyne_demo does around this line: https://github.com/fyne-io/fyne/blob/c29a0624ed96ba1b8f45d903b6941824d50e0502/cmd/fyne_demo/tutorials/widget.go#L359

    Implementing Tapped(e *fyne.PointEvent) is the key.