6

I use Qt and I want to move some object with mouse. For example, user clicks on object and drag this object to another place of window. How I can do it?

I tried mouseMoveEvent:

void QDropLabel::mouseMoveEvent(QMouseEvent *ev) { this->move(ev->pos()); } 

but unfortunately object moves very strange way. It jumps from place to place.

QDropLabel inherits QLabel. Also it has given a pixmap. I tried to do it with different objects, but result is same.

3
  • 1
    Mouse move event is not for "mouse is dragging something" but literaly mouse (cursor) moved. You have to catch "dragging" somehow. Also ev->pos may be relative to widget Commented Jun 23, 2012 at 21:30
  • I don't want to use it for drag and drop. I just want to move object using mouse. Commented Jun 24, 2012 at 13:45
  • 1
    Ok, but you want object to follow cursor by itself, or make it movable Commented Jun 24, 2012 at 16:27

1 Answer 1

22

Your movable widget must have a QPoint offset member. It will store a position of the cursor click relative to the widget's top left corner:

void DropLabel::mousePressEvent(QMouseEvent *event) { offset = event->pos(); } 

On mouse move event you just move your widget in its parent coordinate system. Note that if you don't subtract offset from the cursor position, your widget will 'jump' so its top left corner will be just under the cursor.

void DropLabel::mouseMoveEvent(QMouseEvent *event) { if(event->buttons() & Qt::LeftButton) { this->move(mapToParent(event->pos() - offset)); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.