Search code examples
c++qtwidgetmouseeventmouse-coordinates

Tracking mouse coordinates in Qt


Let's say I have a widget in main window, and want to track mouse position ONLY on the widget: it means that left-low corner of widget must be local (0, 0).

Q: How can I do this?

p.s. NON of functions below do that.

widget->mapFromGlobal(QCursor::pos()).x();
QCursor::pos()).x();
event->x();

Solution

  • I am afraid, you won't be happy with your requirement 'lower left must be (0,0). In Qt coordinate systems (0,0) is upper left. If you can accept that. The following code...

    setMouseTracking(true); // E.g. set in your constructor of your widget.
    
    // Implement in your widget
    void MainWindow::mouseMoveEvent(QMouseEvent *event){
        qDebug() << event->pos();
    }
    

    ...will give you the coordinates of your mouse pointer in your widget.