Tracking mouse coordinates in Qt

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

Q: How can I do this?

ps The functions below are listed below.

widget->mapFromGlobal(QCursor::pos()).x(); QCursor::pos()).x(); event->x(); 
+4
source share
2 answers

Iโ€™m afraid you wonโ€™t be satisfied with your requirement โ€œthe bottom left should be (0,0). In the Qt coordinate systems (0,0), the top left. If you can accept this. The following code ...

 setMouseTracking(true); // Eg 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 the mouse pointer in your widget.

+7
source

If all you want to do is tell the mouse position in coordinates, as if the lower left corner of the widget was (0,0), and Y increased as you climb, then the code below does this. I think that the reason for the desire for such a code is wrong, since the coordinates of everything else in the specified widget do not work in this way. So why do you want it, I canโ€™t understand, but here you go.

 #include <QApplication> #include <QMouseEvent> #include <QTransform> #include <QLabel> class Window : public QLabel { public: Window(QWidget *parent = 0, Qt::WindowFlags f = 0) : QLabel(parent, f) { setMouseTracking(true); setMinimumSize(100, 100); } void mouseMoveEvent(QMouseEvent *ev) { // vvv That where the magic happens QTransform t; t.scale(1, -1); t.translate(0, -height()+1); QPoint pos = ev->pos() * t; // ^^^ setText(QString("%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(); } 
+4
source

Source: https://habr.com/ru/post/1499948/


All Articles