How to get Mouse Cursor Position on Form in a Python FMX GUI App?

Question:

I’ve built a simple Form using the DelphiFMX GUI Library for Python. The Form has a MouseMove event attached to it.

What I basically want is the X and Y coordinates of the mouse on the Form when you move the mouse around and then display the coordinates in the Caption of the Form.

I tried the following code, but it doesn’t work:

from delphifmx import *

class frmMain(Form):
    def __init__(self, owner):
        self.Width = 800
        self.Height = 500
        self.Caption = "Mouse Position: <X, Y>"

        self.MouseMove = self.FormMouseMoveEvent

    def FormMouseMoveEvent(self, sender, e):
        self.Caption = "Mouse Position: <" + e.X + ", " + e.Y + ">"


def main():
    Application.Initialize()
    Application.Title = "My Application"
    Application.MainForm = frmMain(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

main()

The Form’s caption never changes and always just say "Mouse Position: <X, Y>"


UPDATE:

I think the MouseMove event isn’t being triggered as it should. I’ve changed the code to the following, but the Caption still isn’t updating:

def FormMouseMoveEvent(self, sender, e):
    self.Caption = "Just changing the caption"

Python blank GUI App

Asked By: Shaun Roselt

||

Answers:

I think the issue is that ‘X and Y’ coordinates that are returned by MouseMoveEvent are integers but the self.Caption expects a string:
You can rewrite the FormMouseMoveEvent() as:

def FormMouseMoveEvent(self, sender, e):
    self.Caption = "Mouse Position: <" + str(e.X) + ", " + str(e.Y) + ">"

Hope it helps!

Answered By: Shardul

I want to correct the way you’re triggering the MouseMove Event. It should be self.OnMouseMove, which is similar to the self.OnClose or any other events like self.button1.OnClick. Also, the MouseMove event takes 3 arguments – Shift, X, and Y other than sender itself. The X and Y are of Single type in Delphi, which needs to be converted to String type.

Here’s the fixed code:

from delphifmx import *

class frmMain(Form):
    def __init__(self, owner):
        self.Width = 800
        self.Height = 500
        self.Caption = "Mouse Position: <X, Y>"

        self.onMouseMove = self.FormMouseMoveEvent

    def FormMouseMoveEvent(self, sender, Shift, X, Y):
        self.Caption = "Mouse Position: <" + str(X) + ", " + str(Y) + ">"


def main():
    Application.Initialize()
    Application.Title = "My Application"
    Application.MainForm = frmMain(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

main()
Answered By: kunarapu priyatham