PopupMenu position property not working properly

Godot Version

4.6.3.stable

Question

I’m seeing some very strange behavior from PopupMenu. When I try to use the following code in my context menu:

func _on_about_to_popup() -> void:
	position = get_mouse_position()

The position that the popup appears is perfectly on the mouse the first click. Any further clicks to open the context menu range wildly all over the place. And half the time the x position value doesn’t even set properly even when the value is wrong. Is this a bug?

Unlikely this is a bug. Far more likely you just don’t understand what is going on.

get_global_mouse_position

get_local_mouse_position

PopupMenu is a Window object, not CanvasItem, which is why I used get_mouse_position. Is there a problem with using get_mouse_position in a Window object?

Again. not likely.

You need to view the simplicity of your code against the likelihood that someone else in the Godot community would have seen this behavior before you did. If this was truly an issue, I strongly suspect it would have been seen and fixed well before now.

I am more inclined to believe that you do not know why what you are seeing is the correct behavior.

I figured out why this was happening! Since PopupMenu is a Window, it is also a Viewport, so when you call get_mouse_position() on a PopupMenu, it’s basically getting the mouse position relative to the PopupMenu’s current position, since the PopupMenu is the origin point of the coordinate system that the mouse position was found on. To fix my code, all I needed to do was change the position assignment to this:
position += Vector2i(get_mouse_position())