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());
}
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 codewill move the upper left corner of
Areaobject to the mouse cursor position ONLY ifAreaobject 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 tomove(parentWidget()->mapFromGlobal(QCursor::pos()));.