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
QPoint(255,136)
QPoint(0,0)
QPoint(255,136)
On a large window:
QPoint(205,86)
QPoint(0,0)
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 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()));
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With