Tracking mouse coordinates in Qt
Asked Answered
L

2

6

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();
Lamont answered 31/8, 2013 at 18:17 Comment(0)
F
10

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.

Flying answered 31/8, 2013 at 19:31 Comment(4)
I know that, and the exact thing I want to do is to transform it to lower left corner.Lamont
You asked this here: #18551662. This is the 'do it yourself' solution. I assumed, with this question here, you asked for an easier Qt way. I must disappoint you, I am not aware of a way to make Qt switch its coordinate system easily. You will have to do the coordinate transformations yourself. If I were you, I'd try to live with the Qt system. Just to move (0,0) from upper to lower corner will hurt only your program's performance unnecessarily.Flying
OK, let's consider that upper-left corner of WIDGET is (0,0). It anyway give wrong output.Lamont
How far wrong? Works perfectly for me. Upper left corner is (0,0), upper right corner is (width,0), lower left corner is (0, height), lower right corner is (width,height). Tracking only within the widget.Flying
M
7

If all you want to do is to report position of the mouse in coordinates as if the widget's lower-left corner was (0,0) and Y was ascending when going up, then the code below does it. I think the reason for wanting such code is misguided, though, since coordinates of everything else within said widget don't work this way. So why would you want it, I can't fathom, but here you go.

#include <QtWidgets>

class Window : public QLabel {
public:
    Window() {
        setMouseTracking(true);
        setMinimumSize(100, 100);
    }
    void mouseMoveEvent(QMouseEvent *ev) override {
        // vvv That's where the magic happens
        QTransform t;
        t.scale(1, -1);
        t.translate(0, -height()+1);
        QPoint pos = ev->pos() * t;
        // ^^^
        setText(QStringLiteral("%1, %2").arg(pos.x()).arg(pos.y()));
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Window w;
    w.show();
    return a.exec();
}
Mycorrhiza answered 2/9, 2013 at 15:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.