4

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());
}
Mykola Tetiuk
  • 157
  • 3
  • 9
  • Please provide a [mcve]. The problem is almost certainly with the way in which you use the value returned by `QCursor::pos` rather than function itself. – G.M. Aug 09 '21 at 07:34
  • It's pretty simple. I'm using `move(QCursor::pos());` inside a widget. As far as I understand it has to attach left-top corner of the widget to the mouse. And it doesn't. – Mykola Tetiuk Aug 09 '21 at 07:43
  • A minimal reproducible example added. – Mykola Tetiuk Aug 09 '21 at 07:47
  • This is a code snippet, it is not a minimal reproducible example. For example it is not clear how you instantiate and show the instance of `Area`. And most important information of all is missing: does the instance have a parent widget....? – HiFile.app - best file manager Aug 09 '21 at 11:11

1 Answers1

4

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()));.