Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 406
Mike Avatar asked Aug 31 '13 18:08

Mike


People also ask

How can I get current cursor position in Qt?

To set or get the position of the mouse cursor use the static methods QCursor::pos() and QCursor::setPos().

How do I show my mouse coordinates?

Once you're in Mouse settings, select Additional mouse options from the links on the right side of the page. In Mouse Properties, on the Pointer Options tab, at the bottom, select Show location of pointer when I press the CTRL key, and then select OK. To see it in action, press CTRL.

How do I find my cursor coordinates in Python?

Practical Data Science using Python Generally, the mouse pointer and its motion are tracked for the purpose of building a screensaver, 2D or 3D games. In order to print the coordinates of the pointer, we have to bind the Motion with a callback function that gets the position of the pointer in x and y variables.


2 Answers

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.

like image 114
Greenflow Avatar answered Sep 23 '22 11:09

Greenflow


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();
}
like image 25
Kuba hasn't forgotten Monica Avatar answered Sep 21 '22 11:09

Kuba hasn't forgotten Monica