Moving object with mouse

LosYear picture LosYear · Jun 23, 2012 · Viewed 19k times · Source

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.

Answer

hank picture hank · Jun 25, 2012

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));
    }
}