Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QCursor::pos(); renders wrong coordinates

Tags:

qt

qt5

qt5.12

I have a floating widget which should follow mouse. Now I have another widget, which sometimes changes its position.

Before any other widgets resize, everything's ok. After the change my coordinates always go astray and the floating widget is shifted, it floats at a distance from the mouse. I've noticed that the shift is somehow connected to window size, it grows when the size is bigger.

I pass to widget mouse coordinates with QCursor::pos();, and I also tried sending QPoint from other background widgets, over which it should float with mouseMoveEvent(QMouseEvent *event) and then QPoint{ mapToGlobal( { event->pos() } )};. These both render the same coordinates, and the same shift occurs.

E.g. On a small window

  • Floater's coordinates QPoint(255,136)
  • Another widget's coordinates: QPoint(0,0)
  • MapToGlobal from another widget: QPoint(255,136)

On a large window:

  • Floater's coordinates QPoint(205,86)
  • Another widget's coordinates: QPoint(0,0)
  • MapToGlobal from another widget: QPoint(205,86)

Can't grasp the problem, why it renders wrong coordinates. The system is Qt 5.12.3. Any help will be appreciated.


UPD: The minimal reproducible example.

.h

class Area : public QWidget
{
    Q_OBJECT

public:
    void moveArea();

};

.cpp

void moveArea::Area()
{
    move(QCursor::pos());
}
like image 275
Mykola Tetiuk Avatar asked Sep 10 '25 01:09

Mykola Tetiuk


1 Answers

QCursor::pos() returns global (i.e. screen) coordinates but widget's position is measured in its parent's coordinate system if it has a parent. And is measured in global coordinates if and ONLY if the widget does not have any parent. So this code

void Area::moveArea()
{
   move(QCursor::pos());
}

will move the upper left corner of Area object to the mouse cursor position ONLY if Area object is a top-level window, i.e. when it has no parent. If it has parent (which I believe is your case), you need to map global coordinates to parent's coordinates by changing your code to move(parentWidget()->mapFromGlobal(QCursor::pos()));.

like image 76
V.K. Avatar answered Sep 13 '25 05:09

V.K.