Luke Cauthen
Luke Cauthen

Reputation: 730

Qt move widget to cursor position

I am implementing a function (Using Qt) that is supposed to move a widget to the cursor position as part of a drag and drop functionality.

I have three events that get triggered, mouse down, mouse move, and mouse up. When the mouse moves and is down, a signal is sent to the widget to move itself to the cursor; however, I have encountered some strange behavior.

This simple code:

void Block::moveToCursor()
{
    block->move(block->mapFromGlobal(QCursor::pos()));
    qDebug() << block->mapFromGlobal(QCursor::pos());
}

where "block" is a QLabel that is a member of Block and is a child of the window's central widget.

It produces this result:

enter image description here

As it can be seen in the debug output, the coordinates are flip flopping (or flickering) every time there is a pixel move. The first coordinated are correct but the second set of coordinates seem to be relative to the top right corner of the window.

I have tried all the mapping functions:

block->move(block->mapFromParent(QCursor::pos()));

-Produces a similar result with the second set of coordinates relative to the center of the window.

block->move(block->mapFrom(this->block, QCursor::pos()));

-This produces an even stranger result. The block does not flicker and moves correctly with respect to the mouse, but the initial position of the block seems to be off by the distance from the top right corner of the computer screen. It also only shows one point when printed out in debug, yet it is moving on the screen. Every time you see Continue Drag, the mouse has moved at least one pixel.

enter image description here

Can someone explain this strange behavior to me and show me the correct way of moving the widget to the cursor at the exact position from where it was originally clicked?

Upvotes: 2

Views: 6835

Answers (1)

Manuel Arwed Schmidt
Manuel Arwed Schmidt

Reputation: 3596

To get the coordinate in relation to the parent (like wanted from move()-Method), you need to use the mapFromGlobal on the parent like this:

block->move(block->parentWidget()->mapFromGlobal(QCursor::pos()));

Just give it a try. The reason for this is, lets consider what happens when you are at position 1,1 inside the child. But the child is for example at position 123,123 from its parent top-left. You would now move it to 1,1, causing it to jump 122 pixels each.

Upvotes: 3

Related Questions